"""Capture a real signed upload request, for the CMS's cross-language test.

The CMS and this platform each verify signatures in their own language. Testing
each against its own fake proves only that a language agrees with itself. This
emits exactly what the real CmsClient puts on the wire — its JSON encoding, its
base64, its HMAC — so the CMS can replay those bytes and prove the two agree.

    python scripts/emit_upload.py > /dev/null   # writes the fixture

Copy the output to the CMS repo at:

    tests/Feature/Agent/fixtures/python_upload_request.json

Regenerate whenever the signing scheme, the canonical message, or the upload
payload shape changes — a stale fixture would keep passing against a contract
neither side implements any more.

Nothing here contacts a network. urlopen is replaced before any call is made, so
this is safe to run against a production-shaped config, and the credentials below
are fixtures rather than anything real.
"""

from __future__ import annotations

import json
import sys
import urllib.request
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from app.api.client import CmsClient  # noqa: E402
from app.config.settings import Settings  # noqa: E402

# Must match what the CMS test creates its agent with.
API_KEY = "tpa_crosslang_key"
API_SECRET = "S3cret" * 10

OUTPUT = Path(__file__).resolve().parent.parent / "tests" / "fixtures" / "python_upload_request.json"

captured: dict[str, object] = {}


def _capture(request, *args, **kwargs):  # noqa: ANN001, ARG001
    captured.update(
        url=request.full_url,
        method=request.get_method(),
        headers=dict(request.header_items()),
        body=request.data.decode("utf-8"),
    )

    raise RuntimeError("captured")


def main() -> None:
    urllib.request.urlopen = _capture  # noqa: S310 - deliberately disabled

    document = OUTPUT.parent / "cnic.jpg"
    document.parent.mkdir(parents=True, exist_ok=True)

    # Deliberately not valid UTF-8: a real document is a JPEG, and any layer
    # that treats the payload as text corrupts it silently.
    document.write_bytes(b"pretend-image-bytes-\xff\xd8\xff")

    cms = CmsClient(
        Settings(cms_base_url="https://cms.test", agent_api_key=API_KEY, agent_api_secret=API_SECRET)
    )

    try:
        cms.upload_document(
            client_id=1,
            path=document,
            document_type="cnic_front",
            title="CNIC Front",
            # Non-ASCII on purpose: Python escapes it as \uXXXX and PHP does not,
            # so a CMS that re-encoded the body before verifying would fail here.
            notes="Urdu: کارڈ",
        )
    except RuntimeError:
        pass

    OUTPUT.write_text(json.dumps(captured, indent=2), encoding="utf-8")

    print(f"Wrote {OUTPUT}")
    print("Copy to the CMS at tests/Feature/Agent/fixtures/python_upload_request.json")


if __name__ == "__main__":
    main()
