#!/usr/bin/env python3
# /// script
# requires-python = ">=3.12,<3.13"
# ///
# How to run:
# uv run --python 3.12 first_customer_deployment_controller.py --help
"""Permission-sealed v1.1 deployment and gateway-start controller."""

from __future__ import annotations

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

from first_customer_deployment_operations import (
    deployment_preflight,
    install_runtime,
    provider_check,
    start_gateway,
)
from first_customer_deployment_permission import verify_deployment_permission
from first_customer_invite_contract import ControllerError


HERE = Path(__file__).resolve().parent
OPERATIONS = HERE / "first_customer_deployment_operations.py"
PERMISSION_MODULE = HERE / "first_customer_deployment_permission.py"


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "mode",
        choices=("preflight", "install", "provider-check", "start"),
    )
    parser.add_argument("--profile", type=Path, required=True)
    parser.add_argument("--permission", type=Path, required=True)
    parser.add_argument("--receipt", type=Path, required=True)
    return parser


def main(argv: Sequence[str] | None = None) -> int:
    args = _parser().parse_args(argv)
    try:
        permission = verify_deployment_permission(
            args.mode,
            args.profile,
            args.permission,
            args.receipt,
            Path(__file__).resolve(),
            OPERATIONS,
            PERMISSION_MODULE,
        )
        operation = {
            "preflight": deployment_preflight,
            "install": install_runtime,
            "provider-check": provider_check,
            "start": start_gateway,
        }[args.mode]
        operation(permission, args.receipt)
    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())
