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

Same purpose as emit_upload.py, for the endpoint that matters now: testing each
side against its own fake proves only that a language agrees with itself. This
emits exactly what the real CmsClient puts on the wire so the CMS can replay
those bytes.

    python scripts/emit_proposal.py

Copy the output to the CMS repo at:

    tests/Feature/Agent/fixtures/python_proposal_request.json

Regenerate whenever the signing scheme or the proposal payload changes — a stale
fixture keeps passing against a contract neither side implements any more.

Nothing here contacts a network: urlopen is replaced before any call is made.
"""

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

API_KEY = "tpa_crosslang_key"
API_SECRET = "S3cret" * 10

OUTPUT = Path(__file__).resolve().parent.parent / "tests" / "fixtures" / "python_proposal_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 / "proposal.jpg"
    document.parent.mkdir(parents=True, exist_ok=True)

    # Not valid UTF-8, on purpose: 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.submit_proposal(
            {
                "idempotency_key": "crosslang-run:file",
                "workflow_id": "crosslang-run",
                "workflow_name": "document_intake",
                "step_name": "file",
                "type": "document.file",
                "tool_name": "submit_filing_proposal",
                "tool_version": "1.0.0",
                "agent_version": "0.9.0",
                "confidence": 0.93,
                "payload": {
                    "client_id": 1,
                    "document_type": "cnic_front",
                    "title": "CNIC Front",
                    "candidates": [
                        {"id": 1, "name": "Muhammad Ali", "file_number": "LA-0001",
                         "match_reason": "CNIC on the document matched exactly"}
                    ],
                },
                # Non-ASCII on purpose: Python escapes it as \uXXXX and PHP does
                # not, so a CMS that re-encoded the body before verifying would
                # pass every same-language test and fail this one.
                "evidence": {"readable": True, "text": "شناختی کارڈ 35202-1234567-1",
                             "fields": {"cnic": {"value": "35202-1234567-1"}}},
                "events": [
                    {"event": "ocr", "occurred_at": "2026-07-28T10:00:00+00:00",
                     "message": "Read 14 blocks"},
                    {"event": "identified", "occurred_at": "2026-07-28T10:00:09+00:00"},
                ],
                "warnings": ["Resubmitted after review"],
            },
            path=document,
        )
    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_proposal_request.json")


if __name__ == "__main__":
    main()
