#!/usr/bin/env python3
"""Verify Working Leo production-apply authorization text.

This verifier checks that an operator authorization sentence exactly matches
the retained authorization template after substituting the fresh deployed SHA.
It is intentionally non-mutating: it never opens a database connection, never
runs SQL, and never marks production apply as executed.
"""

from __future__ import annotations

import argparse
import json
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

REPORT_DIR = Path("docs/reports/leo-working-state-20260709")
DEFAULT_AUTH_PACKET = REPORT_DIR / "working-leo-production-apply-authorization-packet-current.json"
DEFAULT_OUT = REPORT_DIR / "working-leo-production-apply-authorization-verification-current.json"
DEFAULT_MARKDOWN_OUT = REPORT_DIR / "working-leo-production-apply-authorization-verification-current.md"

SHA_RE = re.compile(r"[0-9a-f]{7,40}")


def _load_json(path: Path) -> dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8"))


def expected_authorization_text(auth_packet: dict[str, Any], deployed_sha: str) -> str:
    template = str(auth_packet["explicit_operator_authorization_text_template"])
    return template.replace("<DEPLOYED_SHA_READBACK>", deployed_sha)


def _normalize_text(value: str) -> str:
    return " ".join(value.strip().split())


def verify_authorization(
    *,
    deployed_sha: str,
    authorization_text: str = "",
    operator_identity: str = "",
    auth_packet_path: Path = DEFAULT_AUTH_PACKET,
) -> dict[str, Any]:
    auth_packet = _load_json(auth_packet_path)
    expected_text = (
        expected_authorization_text(auth_packet, deployed_sha)
        if deployed_sha
        else expected_authorization_text(auth_packet, "<DEPLOYED_SHA_READBACK>")
    )
    checks = {
        "auth_packet_ready": auth_packet.get("ready_to_request_authorization") is True,
        "auth_packet_not_authorized": auth_packet.get("production_apply_authorization_present") is False,
        "auth_packet_not_executed": auth_packet.get("production_apply_executed") is False,
        "deployed_sha_shape": bool(SHA_RE.fullmatch(deployed_sha)),
        "operator_identity_present": bool(operator_identity.strip()),
        "authorization_text_present": bool(authorization_text.strip()),
        "authorization_text_matches_expected": bool(expected_text)
        and _normalize_text(authorization_text) == _normalize_text(expected_text),
        "telegram_visible_post_not_authorized": auth_packet.get("authorization_scope", {}).get(
            "telegram_visible_post_authorized"
        )
        is False,
    }
    safe_to_enter_apply_window = all(checks.values())
    if safe_to_enter_apply_window:
        status = "authorization_verified_not_executed"
    elif not checks["deployed_sha_shape"]:
        status = "missing_fresh_deployed_sha"
    elif not checks["authorization_text_present"]:
        status = "missing_authorization_text"
    elif not checks["authorization_text_matches_expected"]:
        status = "authorization_text_mismatch"
    else:
        status = "authorization_not_ready"
    return {
        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
        "mode": "authorization_verification_only",
        "status": status,
        "safe_to_enter_apply_window": safe_to_enter_apply_window,
        "production_apply_executed": False,
        "production_apply_authorization_present": safe_to_enter_apply_window,
        "auth_packet_path": str(auth_packet_path),
        "deployed_sha": deployed_sha,
        "operator_identity": operator_identity,
        "checks": checks,
        "expected_authorization_text": expected_text,
        "fresh_deployed_sha_required": not checks["deployed_sha_shape"],
        "provided_authorization_text_hashable_length": len(_normalize_text(authorization_text)),
        "next_action_if_verified": [
            "Re-run production preflight immediately before each packet phase.",
            "Run apply and postflight SQL in the retained manifest order.",
            "Capture apply/postflight/regression/service/cleanup logs in the session-plan paths.",
            "Write and validate the production receipt before claiming canonical rows changed.",
        ],
        "claim_ceiling": (
            "This verifier only checks whether an authorization string is valid for the current deployed SHA. It does "
            "not run SQL, does not mutate production, and does not prove canonical rows were changed."
        ),
    }


def write_json(path: Path, data: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")


def write_markdown(path: Path, data: dict[str, Any]) -> None:
    lines = [
        "# Working Leo Production Apply Authorization Verification",
        "",
        f"Generated UTC: `{data['generated_at_utc']}`",
        f"Mode: `{data['mode']}`",
        f"Status: `{data['status']}`",
        f"Safe to enter apply window: `{data['safe_to_enter_apply_window']}`",
        f"Production apply executed: `{data['production_apply_executed']}`",
        f"Production apply authorization present: `{data['production_apply_authorization_present']}`",
        f"Deployed SHA: `{data['deployed_sha']}`",
        f"Operator identity: `{data['operator_identity']}`",
        "",
        "## Checks",
        "",
    ]
    for key, value in sorted(data["checks"].items()):
        lines.append(f"- `{key}`: `{value}`")
    lines.extend(["", "## Expected Authorization Text", "", data["expected_authorization_text"] or "(missing)", ""])
    lines.extend(["## Next Action If Verified", ""])
    lines.extend(f"- {item}" for item in data["next_action_if_verified"])
    lines.extend(["", "## Claim Ceiling", "", data["claim_ceiling"], ""])
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("\n".join(lines), encoding="utf-8")


def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--auth-packet", type=Path, default=DEFAULT_AUTH_PACKET)
    parser.add_argument("--deployed-sha", default="")
    parser.add_argument("--authorization-text", default="")
    parser.add_argument("--authorization-text-file", type=Path)
    parser.add_argument("--operator-identity", default="")
    parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
    parser.add_argument("--markdown-out", type=Path, default=DEFAULT_MARKDOWN_OUT)
    return parser.parse_args(argv)


def main(argv: list[str] | None = None) -> int:
    args = parse_args(argv)
    authorization_text = args.authorization_text
    if args.authorization_text_file is not None:
        authorization_text = args.authorization_text_file.read_text(encoding="utf-8")
    data = verify_authorization(
        deployed_sha=args.deployed_sha,
        authorization_text=authorization_text,
        operator_identity=args.operator_identity,
        auth_packet_path=args.auth_packet,
    )
    write_json(args.out, data)
    write_markdown(args.markdown_out, data)
    print(
        json.dumps(
            {
                "out": str(args.out),
                "markdown_out": str(args.markdown_out),
                "safe_to_enter_apply_window": data["safe_to_enter_apply_window"],
                "status": data["status"],
            },
            indent=2,
            sort_keys=True,
        )
    )
    return 0 if data["safe_to_enter_apply_window"] else 2


if __name__ == "__main__":
    raise SystemExit(main())
