#!/usr/bin/env python3
# /// script
# requires-python = ">=3.12,<3.13"
# ///
# How to run:
# uv run --python 3.12 first_customer_invite_controller.py --help
"""Permission-sealed one-use v1.1 first-customer invite controller."""

from __future__ import annotations

import argparse
import json
import subprocess
import sys
from pathlib import Path
from typing import Sequence

from first_customer_invite_contract import (
    CANDIDATE,
    ControllerError,
    clean_baseline,
    exclusive_json,
)
from first_customer_invite_permission import verify_permission
from first_customer_invite_operations import prepare_invite, verify_invite


HERE = Path(__file__).resolve().parent
CONTRACT = HERE / "first_customer_invite_contract.py"
OPERATIONS = HERE / "first_customer_invite_operations.py"
PERMISSION_MODULE = HERE / "first_customer_invite_permission.py"


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("mode", choices=("preflight", "prepare", "verify"))
    parser.add_argument("--profile", type=Path, required=True)
    parser.add_argument("--draft", type=Path, required=True)
    parser.add_argument("--permission", type=Path, required=True)
    parser.add_argument("--receipt", type=Path, required=True)
    parser.add_argument("--handoff", type=Path)
    parser.add_argument("--session-id")
    parser.add_argument("--sid-hash")
    return parser


def main(argv: Sequence[str] | None = None) -> int:
    args = _parser().parse_args(argv)
    try:
        verify_permission(
            args.mode,
            args.profile,
            args.draft,
            args.permission,
            Path(__file__).resolve(),
            CONTRACT,
            OPERATIONS,
            PERMISSION_MODULE,
            args.receipt,
            args.handoff,
        )
        if args.mode == "preflight":
            draft = clean_baseline(args.profile, args.draft)
            exclusive_json(
                args.receipt,
                {
                    "schema": "dualcoach-first-customer-preflight-receipt-v1",
                    "status": "PASS_READY",
                    "candidate_digest": CANDIDATE,
                    "customer_key": draft.customer_key,
                    "mutations": 0,
                },
            )
        elif args.mode == "prepare" and args.handoff is not None:
            prepare_invite(args.profile, args.draft, args.handoff, args.receipt)
        elif (
            args.mode == "verify"
            and args.handoff is not None
            and args.session_id is not None
            and args.sid_hash is not None
        ):
            verify_invite(
                args.profile,
                args.handoff,
                args.session_id,
                args.sid_hash,
                args.receipt,
            )
        else:
            raise ControllerError("mode arguments are incomplete")
    except (
        ControllerError,
        OSError,
        ValueError,
        KeyError,
        TypeError,
        subprocess.SubprocessError,
    ) as exc:
        sys.stderr.write(f"FAIL: {exc}\n")
        return 2
    print(json.dumps({"mode": args.mode, "receipt": str(args.receipt), "status": "PASS"}))
    return 0


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