#!/usr/bin/env python3
import json
from pathlib import Path

SOURCE = Path("source-bestiary/local-newserv/system/tables/battle-params.json")
OUT = Path("site/generated/bestiary/bb")

DIFFICULTY_ORDER = {
    "Normal": 0,
    "Hard": 1,
    "Very Hard": 2,
    "Ultimate": 3,
}

def label_episode(table_name):
    ep, mode = table_name.split("-", 1)
    return ep.replace("Episode", "Episode "), mode

def enemy_label(value):
    return str(value).replace("_", " ").title()

def main():
    data = json.loads(SOURCE.read_text())
    OUT.mkdir(parents=True, exist_ok=True)

    rows = []

    for table_name, difficulties in data.items():
        episode, mode = label_episode(table_name)

        for difficulty, entries in difficulties.items():
            for entry in entries:
                stats = entry.get("Stats", {})
                resist = entry.get("ResistData", {})
                enemies = stats.get("Enemies") or []

                for enemy in enemies:
                    rows.append({
                        "version": "bb",
                        "episode": episode,
                        "mode": mode,
                        "difficulty": difficulty,
                        "enemy": enemy_label(enemy),
                        "enemy_key": enemy,
                        "bp_index": entry.get("BPIndex"),
                        "hp": stats.get("HP", 0),
                        "atp": stats.get("ATP", 0),
                        "dfp": stats.get("DFP", 0),
                        "mst": stats.get("MST", 0),
                        "ata": stats.get("ATA", 0),
                        "evp": stats.get("EVP", 0),
                        "lck": stats.get("LCK", 0),
                        "esp": stats.get("ESP", 0),
                        "exp": stats.get("EXP", 0),
                        "meseta": stats.get("Meseta", 0),
                        "efr": resist.get("EFR", 0),
                        "eic": resist.get("EIC", 0),
                        "eth": resist.get("ETH", 0),
                        "elt": resist.get("ELT", 0),
                        "edk": resist.get("EDK", 0),
                    })

    rows.sort(key=lambda row: (
        row["episode"],
        row["mode"],
        DIFFICULTY_ORDER.get(row["difficulty"], 999),
        row["enemy"],
        row["bp_index"] if row["bp_index"] is not None else 9999,
    ))

    (OUT / "bb.json").write_text(json.dumps(rows, indent=2, sort_keys=True) + "\n")
    (OUT / "index.json").write_text(json.dumps({
        "mode": "bestiary",
        "label": "BB",
        "tables": [{
            "version": "bb",
            "label": "BB",
            "path": "bb.json",
            "rows": len(rows),
        }],
    }, indent=2, sort_keys=True) + "\n")

    print(f"bb: {len(rows)} rows -> {OUT / 'bb.json'}")
    print(f"index -> {OUT / 'index.json'}")

if __name__ == "__main__":
    main()
