"""
Orchestrates the full .mhd -> JSON conversion for the Homecoming database
bundled with Mids Reborn, and copies over the files Mids already ships as JSON.

Usage: python3 build_all.py [source_db_dir] [output_dir]
"""
import json
import os
import shutil
import sys
import time

from enhdb_parser import parse_enhdb
from powers_parser import parse_powers_db
from text_db_parser import parse_origins, parse_eclasses, parse_maths, parse_levels

DEFAULT_SRC = "/home/claude/mids-reborn/MidsReborn/Databases/Homecoming"
DEFAULT_OUT = "/home/claude/coh-data-pipeline/out"


def write_json(obj, path):
    with open(path, "w", encoding="utf-8") as f:
        json.dump(obj, f, separators=(",", ":"))
    size_mb = os.path.getsize(path) / (1024 * 1024)
    print(f"  wrote {path} ({size_mb:.2f} MB)")


def main():
    src = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_SRC
    out = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_OUT
    os.makedirs(out, exist_ok=True)

    t0 = time.time()

    print("Parsing EnhDB.mhd ...")
    enh = parse_enhdb(os.path.join(src, "EnhDB.mhd"))
    write_json(enh["enhancements"], os.path.join(out, "enhancements.json"))
    write_json(enh["enhancement_sets"], os.path.join(out, "enhancement_sets.json"))

    print("Parsing I12.mhd ...")
    db = parse_powers_db(os.path.join(src, "I12.mhd"), progress_every=3000)
    write_json(db["meta"], os.path.join(out, "db_meta.json"))
    write_json(db["archetypes"], os.path.join(out, "archetypes.json"))
    write_json(db["powersets"], os.path.join(out, "powersets.json"))
    write_json(db["powers"], os.path.join(out, "powers.json"))
    write_json(db["entities"], os.path.join(out, "entities.json"))

    print("Parsing text databases ...")
    write_json(parse_origins(os.path.join(src, "Origins.mhd")), os.path.join(out, "origins.json"))
    write_json(parse_eclasses(os.path.join(src, "EClasses.mhd")), os.path.join(out, "enhancement_classes.json"))
    write_json(parse_maths(os.path.join(src, "Maths.mhd")), os.path.join(out, "maths_ed_schedules.json"))
    write_json(parse_levels(os.path.join(src, "NLevels.mhd")), os.path.join(out, "levels_normal.json"))
    write_json(parse_levels(os.path.join(src, "RLevels.mhd")), os.path.join(out, "levels_respec.json"))

    print("Copying already-JSON files Mids ships directly ...")
    for fname in ["TypeGrades.json", "Compare.json", "AttribMod.json"]:
        src_path = os.path.join(src, fname)
        if os.path.exists(src_path):
            dst_path = os.path.join(out, fname)
            shutil.copyfile(src_path, dst_path)
            size_mb = os.path.getsize(dst_path) / (1024 * 1024)
            print(f"  copied {dst_path} ({size_mb:.2f} MB)")

    elapsed = time.time() - t0
    print(f"\nDone in {elapsed:.1f}s. Output in {out}/")

    total_size = sum(
        os.path.getsize(os.path.join(out, f))
        for f in os.listdir(out)
        if os.path.isfile(os.path.join(out, f))
    )
    print(f"Total output size: {total_size / (1024 * 1024):.1f} MB")


if __name__ == "__main__":
    main()
