#!/usr/bin/env python3
"""Migrace poskozenych JSON konverzaci (Title-Dict Bug)."""
from __future__ import annotations

import argparse
import json
import os
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path


def default_dir() -> Path:
    env = os.environ.get("CB26_CONVERSATIONS_DIR")
    if env:
        return Path(env).expanduser()
    try:
        from cyberbrain26.paths import conversations_dir
        return conversations_dir()
    except Exception:
        return Path.cwd() / "data" / "conversations"


def coerce_title(raw) -> str:
    if isinstance(raw, dict):
        raw = raw.get("title", "Nova konverzace")
    if raw is None or (isinstance(raw, str) and not raw.strip()):
        return "Nova konverzace"
    return str(raw).strip()


def migrate_one(path: Path, dry_run: bool) -> str:
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except Exception as e:
        print(f"  [SKIP] {path.name}: {e}")
        return "skip"
    raw = data.get("title")
    needs_fix = isinstance(raw, dict) or raw is None or (
        isinstance(raw, str) and not raw.strip()
    )
    if not needs_fix:
        return "ok"
    old_repr = repr(raw)[:80]
    new_title = coerce_title(raw)
    data["title"] = new_title
    now = datetime.now(timezone.utc).isoformat()
    data.setdefault("created_at", now)
    data.setdefault("updated_at", now)
    data.setdefault("history", [])
    print(f"  [FIX ] {path.name}: {old_repr} -> {new_title!r}")
    if not dry_run:
        shutil.copy2(path, path.with_suffix(path.suffix + ".premigrate"))
        path.write_text(
            json.dumps(data, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )
    return "fixed"


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--dir", type=Path, default=default_dir())
    ap.add_argument("--dry-run", action="store_true")
    args = ap.parse_args()
    d: Path = args.dir
    print(f"Adresar: {d}")
    if not d.exists():
        print("Adresar neexistuje.", file=sys.stderr)
        return 2
    files = sorted(d.glob("*.json"))
    print(f"Nalezeno {len(files)} JSON souboru.\n")
    stats = {"ok": 0, "fixed": 0, "skip": 0}
    for f in files:
        stats[migrate_one(f, args.dry_run)] += 1
    print()
    print(f"OK:    {stats['ok']}")
    print(f"Fixed: {stats['fixed']}")
    print(f"Skip:  {stats['skip']}")
    if args.dry_run:
        print("\n[dry-run] Nic nebylo zapsano.")
    else:
        print("\nZalohy ulozeny jako *.premigrate")
    return 0


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