#!/usr/bin/env python3
"""Record a retained direct-claim handler suite JSON emitted by the VPS runner."""

from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[1]
REPORT_DIR = ROOT / "docs" / "reports" / "leo-working-state-20260709"
DEFAULT_OUT = REPORT_DIR / "telegram-handler-direct-claim-suite-current.json"

SECRET_PATTERNS = [
    re.compile(r"\b\d{6,}:[A-Za-z0-9_-]{20,}\b"),
    re.compile(r"(Authorization: Bearer )([A-Za-z0-9._-]+)", re.IGNORECASE),
    re.compile(r"((?:api[_-]?key|token|secret|password)[=:]\s*)([A-Za-z0-9._-]+)", re.IGNORECASE),
]


def redact(text: str) -> str:
    result = text
    for pattern in SECRET_PATTERNS:
        if pattern.groups >= 2:
            result = pattern.sub(r"\1[REDACTED]", result)
        else:
            result = pattern.sub("[REDACTED_TOKEN]", result)
    return result


def parse_report(raw: str) -> dict[str, Any]:
    cleaned = redact(raw).strip()
    for line in reversed(cleaned.splitlines()):
        candidate = line.strip()
        if not candidate.startswith("{"):
            continue
        return json.loads(candidate)
    raise ValueError("stdin contained no JSON object line")


def record_report(report: dict[str, Any], *, out: Path = DEFAULT_OUT) -> dict[str, Any]:
    report = dict(report)
    report["source_report_path"] = str(out)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    return report


def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
    return parser.parse_args(argv)


def main(argv: list[str] | None = None) -> int:
    args = parse_args(argv)
    report = record_report(parse_report(sys.stdin.read()), out=args.out)
    print(
        json.dumps(
            {
                "out": str(args.out),
                "pass_runtime": report.get("pass_runtime"),
                "results": len(report.get("results") or []),
                "posted_to_telegram": report.get("posted_to_telegram"),
                "db_counts_changed": report.get("db_counts_changed"),
                "temp_profile_removed": report.get("temp_profile_removed"),
            },
            indent=2,
            sort_keys=True,
        )
    )
    return 0 if report.get("pass_runtime") else 1


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