#!/usr/bin/env python3
"""Import .data/interview_sessions/*.json into Postgres interview_sessions.

Usage (from repo root, venv active):

    python scripts/migrate_sessions_to_pg.py
    python scripts/migrate_sessions_to_pg.py --dir .data/interview_sessions --dry-run

Skips rows when DB checkpoint_version is already >= file version.
"""

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 main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--dir",
        type=Path,
        default=ROOT / ".data" / "interview_sessions",
        help="Directory of session JSON checkpoints",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Parse and report only; do not write",
    )
    parser.add_argument(
        "--force",
        action="store_true",
        help="Overwrite even when DB version is newer/equal",
    )
    args = parser.parse_args()

    from app.database import DATABASE_URL, ensure_schema
    from app.services.interviews.session_db import upsert_from_payload

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

    if not args.dry_run:
        ensure_schema()

    files = sorted(args.dir.glob("*.json"))
    if not files:
        print("No JSON checkpoints found.")
        return 0

    counts = {"inserted": 0, "updated": 0, "skipped": 0, "error": 0}
    for path in files:
        try:
            payload = json.loads(path.read_text(encoding="utf-8"))
        except Exception as exc:  # noqa: BLE001
            print(f"  ERROR read {path.name}: {exc}")
            counts["error"] += 1
            continue
        iid = payload.get("interview_id") or path.stem
        ver = payload.get("checkpoint_version")
        if args.dry_run:
            print(f"  would import {iid} v={ver}")
            continue
        try:
            action = upsert_from_payload(payload, only_if_newer=not args.force)
            counts[action] = counts.get(action, 0) + 1
            print(f"  {action:8} {iid} (file v={ver})")
        except Exception as exc:  # noqa: BLE001
            print(f"  ERROR  {iid}: {exc}")
            counts["error"] += 1

    print("Done:", counts)
    return 1 if counts["error"] else 0


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