"""
AutoPOE2 — Read-only Content.ggpk extractor → assets/game_data/poe2_ggpk.db

Does not modify the game install. Requires an Oodle/ooz DLL for .datc64 tables.
"""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8")

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from src.assistant_tool.ggpk_extract.oodle import OodleUnavailable  # noqa: E402
from src.assistant_tool.ggpk_extract.paths import find_content_ggpk, find_oodle_dll  # noqa: E402
from src.assistant_tool.ggpk_extract.pipeline import DEFAULT_TABLES, extract, repo_root  # noqa: E402


def main() -> int:
    parser = argparse.ArgumentParser(description="Extract Path of Exile 2 Content.ggpk into SQLite (read-only).")
    parser.add_argument("--ggpk", default=None, help="Path to Content.ggpk")
    parser.add_argument("--db", default=None, help="Output SQLite path")
    parser.add_argument("--schema", default=None, help="dat-schema JSON (schema.min.json)")
    parser.add_argument("--tables", default=",".join(DEFAULT_TABLES), help="Comma-separated .datc64 table names")
    parser.add_argument("--catalog-only", action="store_true", help="Write GGPK catalog + HashCache only")
    args = parser.parse_args()

    ggpk = find_content_ggpk(args.ggpk)
    if ggpk is None:
        print("[error] Content.ggpk not found. Pass --ggpk or set AUTOPOE2_GGPK.")
        return 1

    root = repo_root()
    db_path = Path(args.db) if args.db else root / "assets" / "game_data" / "poe2_ggpk.db"
    schema_path = Path(args.schema) if args.schema else root / "assets" / "game_data" / "schema.min.json"
    tables = tuple(t.strip() for t in args.tables.split(",") if t.strip())

    print("=================================================")
    print("  AutoPOE2 GGPK → SQLite (read-only)")
    print("=================================================")
    print(f"  GGPK   : {ggpk} ({ggpk.stat().st_size:,} bytes)")
    print(f"  DB     : {db_path}")
    print(f"  Schema : {schema_path}")
    print(f"  Oodle  : {find_oodle_dll() or '(missing — catalog only unless --catalog-only)'}")
    print()

    try:
        stats = extract(
            ggpk_path=ggpk,
            db_path=db_path,
            schema_path=schema_path,
            tables=tables,
            catalog_only=args.catalog_only,
        )
    except OodleUnavailable as exc:
        print(f"[error] {exc}")
        return 2
    except Exception as exc:
        print(f"[error] {type(exc).__name__}: {exc}")
        return 1

    print()
    print(f"[done] status={stats.get('status')} db={db_path}")
    for key in ("ggpk_records", "hashcache_records", "logical_files", "dat_tables"):
        if key in stats:
            print(f"        {key}={stats[key]}")
    if stats.get("status") == "catalog-no-oodle":
        print("[hint] Build libooz.dll (zao/ooz, export Ooz_Decompress) into tools/bin/ then re-run.")
        return 2
    return 0


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