"""
AutoPOE2 - GGPK Direct Data Extractor (list / extract uncompressed root files).

For the SQLite game-data pipeline use tools/extract_ggpk_to_db.py.
"""
from __future__ import annotations

import argparse
import os
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.ggpk_fs import GgpkFs  # noqa: E402
from src.assistant_tool.ggpk_extract.paths import DEFAULT_GGPK_PATH, find_content_ggpk  # noqa: E402

# Back-compat for older scripts that imported these names.
Poe2GgpkReader = GgpkFs


def main() -> None:
    parser = argparse.ArgumentParser(description="List or extract uncompressed root files from Content.ggpk")
    parser.add_argument("--ggpk", default=str(DEFAULT_GGPK_PATH), help="Path to Content.ggpk")
    parser.add_argument("--list", action="store_true", help="List Bundles2 + root (default)")
    parser.add_argument("--extract-root-files", action="store_true", help="Extract root .txt/.jpg/.wav")
    parser.add_argument("--out-dir", default="./assets/ggpk_extracted", help="Output directory")
    args = parser.parse_args()

    ggpk = find_content_ggpk(args.ggpk)
    if ggpk is None:
        print(f"[Error] Không tìm thấy: {args.ggpk}")
        return

    print("=================================================")
    print("   AutoPOE2 - GGPK Direct Data Extractor         ")
    print("=================================================")
    with GgpkFs(ggpk) as reader:
        print(f"[GGPK] {ggpk} ({ggpk.stat().st_size:,} bytes)")
        for ent in reader.walk(max_depth=1):
            extra = f"entries={ent.child_count}" if ent.tag == "PDIR" else f"size={ent.data_size:,} B"
            print(f"  [{ent.tag:4s}] {ent.path} ({extra}) @ {hex(ent.offset)}")
            if args.extract_root_files and ent.tag == "FILE" and "/" not in ent.path:
                if ent.name.endswith((".txt", ".jpg", ".wav")):
                    dest = os.path.join(args.out_dir, ent.name)
                    Path(dest).parent.mkdir(parents=True, exist_ok=True)
                    Path(dest).write_bytes(reader.read_payload(ent))
                    print(f"[Extract] {ent.name} -> {dest}")


if __name__ == "__main__":
    main()
