"""Operator inspect/plan for leftover POST /api/contact (8K).

Read-only. Does not migrate, delete leftover runtime, or send email.

  python scripts/inspect_legacy_contact.py --repo PATH
  python scripts/inspect_legacy_contact.py --repos-file paths.txt --out report.json
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from src.domain.codegen.legacy_contact_inspect import (
    inspect_legacy_contact_batch,
    inspect_legacy_contact_report,
)


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Inspect leftover contact runtime on a cloned project repo. Dry-run only."
    )
    parser.add_argument(
        "--repo",
        action="append",
        default=[],
        help="Project clone path (repeatable)",
    )
    parser.add_argument(
        "--repos-file",
        help="Text file of clone paths, one per line",
    )
    parser.add_argument("--out", help="Write JSON report to this path")
    parser.add_argument(
        "--apply",
        action="store_true",
        help=argparse.SUPPRESS,
    )
    return parser


def collect_repos(args: argparse.Namespace) -> list[str]:
    paths = list(args.repo or [])
    if args.repos_file:
        text = Path(args.repos_file).read_text(encoding="utf-8")
        for line in text.splitlines():
            stripped = line.strip()
            if stripped and not stripped.startswith("#"):
                paths.append(stripped)
    return paths


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    if args.apply:
        print(
            "apply is forbidden in 8K; leftover_runtime_removal_ready=no",
            file=sys.stderr,
        )
        return 2
    repos = collect_repos(args)
    if not repos:
        parser.error("provide --repo and/or --repos-file")
    payload = (
        inspect_legacy_contact_batch(repos)
        if len(repos) > 1
        else inspect_legacy_contact_report(repos[0])
    )
    encoded = json.dumps(payload, indent=2)
    if args.out:
        Path(args.out).write_text(encoded + "\n", encoding="utf-8")
    else:
        print(encoded)
    return 0


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