#!/usr/bin/env python3
"""Import face / ID / voice / report metadata from .data/ into Postgres.

Usage (repo root, venv):

    python scripts/migrate_gateway_metadata_to_pg.py
    python scripts/migrate_gateway_metadata_to_pg.py --dry-run
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))


def _import_face(data_dir: Path, *, dry_run: bool) -> dict[str, int]:
    from app.services.face.audit_db import upsert_audit
    from app.services.face.audit_store import FaceAuditRecord

    counts = {"inserted": 0, "error": 0}
    for path in sorted(data_dir.glob("*.jsonl")):
        for line in path.read_text(encoding="utf-8").splitlines():
            if not line.strip():
                continue
            try:
                data = json.loads(line)
                rec = FaceAuditRecord(
                    **{k: data.get(k) for k in FaceAuditRecord.__dataclass_fields__}
                )
                if dry_run:
                    print(f"  face would import {rec.audit_id}")
                    continue
                upsert_audit(rec)
                counts["inserted"] += 1
            except Exception as exc:  # noqa: BLE001
                print(f"  face ERROR {path.name}: {exc}")
                counts["error"] += 1
    return counts


def _import_id(data_dir: Path, *, dry_run: bool) -> dict[str, int]:
    from app.services.id.status_db import upsert_record
    from app.services.id.status_store import IdVerificationRecord

    counts = {"inserted": 0, "error": 0}
    index = data_dir / "status_index.jsonl"
    paths = [index] if index.exists() else []
    paths += sorted((data_dir / "by_interview").glob("*.jsonl")) if (
        data_dir / "by_interview"
    ).is_dir() else []
    seen: set[str] = set()
    for path in paths:
        if not path.exists():
            continue
        for line in path.read_text(encoding="utf-8").splitlines():
            if not line.strip():
                continue
            try:
                data = json.loads(line)
                vid = data.get("verification_id")
                if not vid or vid in seen:
                    continue
                seen.add(vid)
                rec = IdVerificationRecord(
                    **{k: data.get(k) for k in IdVerificationRecord.__dataclass_fields__}
                )
                if dry_run:
                    print(f"  id would import {vid}")
                    continue
                upsert_record(rec)
                counts["inserted"] += 1
            except Exception as exc:  # noqa: BLE001
                print(f"  id ERROR {path.name}: {exc}")
                counts["error"] += 1
    return counts


def _import_voice(data_dir: Path, *, dry_run: bool) -> dict[str, int]:
    from app.services.voice.voice_db import upsert_profile
    from app.services.voice.voice_store import VoiceProfile

    counts = {"inserted": 0, "error": 0}
    for path in sorted(data_dir.glob("*.json")):
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
            profile = VoiceProfile(
                **{k: data.get(k) for k in VoiceProfile.__dataclass_fields__}
            )
            if dry_run:
                print(f"  voice would import {profile.voice_id}")
                continue
            upsert_profile(profile)
            counts["inserted"] += 1
        except Exception as exc:  # noqa: BLE001
            print(f"  voice ERROR {path.name}: {exc}")
            counts["error"] += 1
    return counts


def _import_reports(data_dir: Path, *, dry_run: bool) -> dict[str, int]:
    from app.services.reports.report_db import upsert_from_pdf_path

    counts = {"inserted": 0, "error": 0}
    for path in sorted(data_dir.glob("*.pdf")):
        try:
            if dry_run:
                print(f"  report would import {path.stem}")
                continue
            upsert_from_pdf_path(path)
            counts["inserted"] += 1
        except Exception as exc:  # noqa: BLE001
            print(f"  report ERROR {path.name}: {exc}")
            counts["error"] += 1
    return counts


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--data-root", type=Path, default=ROOT / ".data")
    args = parser.parse_args()

    from app.database import DATABASE_URL, ensure_schema

    safe = DATABASE_URL
    if "@" in safe:
        pre, post = safe.split("@", 1)
        safe = pre.rsplit(":", 1)[0] + ":***@" + post
    print(f"DB: {safe}")
    if not args.dry_run:
        ensure_schema()

    root = args.data_root
    results = {
        "face": _import_face(root / "face_verification_audits", dry_run=args.dry_run),
        "id": _import_id(root / "id_verification" / "status", dry_run=args.dry_run),
        "voice": _import_voice(root / "voice_profiles", dry_run=args.dry_run),
        "reports": _import_reports(root / "reports", dry_run=args.dry_run),
    }
    print("Done:", results)
    errors = sum(v.get("error", 0) for v in results.values())
    return 1 if errors else 0


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