"""
Loads AttribMod.json (Mids Reborn ships this one already as JSON) and mirrors
DatabaseAPI.GetModifier(iClass, iTable, iLevel): every power/bonus effect's
"scale" value is turned into a real magnitude by multiplying against a
per-archetype, per-level table named in the effect's `modifier_table` field.

Verified: "Melee_Ones" / "Ranged_Ones" are flat all-1.0 tables (used by most
global set-bonus percentage effects, e.g. Luck of the Gambler's +7.5% global
recharge, which we found stored as `scale: 0.075` against modifier_table
"Melee_Ones" - confirming final_value = scale * 1.0 = scale for those).
Other tables (e.g. "Melee_HealSelf") vary by archetype/level and are used for
effects like flat HP bonuses, exactly mirroring how a power's own damage/heal
effects are scaled.
"""
import gzip
import json
import os


class AttribMods:
    def __init__(self, path):
        gz_path = path + ".gz"
        if os.path.exists(path):
            with open(path, "r", encoding="utf-8") as f:
                data = json.load(f)
        elif os.path.exists(gz_path):
            with gzip.open(gz_path, "rt", encoding="utf-8") as f:
                data = json.load(f)
        else:
            raise FileNotFoundError(f"Neither {path} nor {gz_path} exists")

        self.by_id = {m["ID"]: m for m in data["Modifier"]}

    def get_modifier(self, table_name, archetype_column, level):
        """level is 0-based here (matches GetModifier's 'zero-based level' contract)."""
        mod = self.by_id.get(table_name)
        if mod is None or archetype_column < 0 or level < 0:
            return 0.0
        table = mod["Table"]
        if level > len(table) - 1:
            return 0.0
        row = table[level]
        if archetype_column > len(row) - 1:
            return 0.0
        return row[archetype_column]

    def is_flat_table(self, table_name):
        mod = self.by_id.get(table_name)
        if mod is None:
            return False
        return all(v == 1.0 for row in mod["Table"] for v in row)


def effect_final_value(attrib_mods, effect, archetype_column, character_level=50):
    """Mirrors the common path: final = scale * GetModifier(class, table, level).
    character_level is 1-based (e.g. 50); GetModifier expects zero-based."""
    table_name = effect.get("modifier_table")
    if not table_name:
        return effect.get("scale", 0.0)
    modifier = attrib_mods.get_modifier(table_name, archetype_column, character_level - 1)
    return effect.get("scale", 0.0) * modifier


if __name__ == "__main__":
    am = AttribMods("/home/claude/coh-data-pipeline/out/AttribMod.json")
    print("Melee_Ones is flat 1.0 table:", am.is_flat_table("Melee_Ones"))
    print("Ranged_Ones is flat 1.0 table:", am.is_flat_table("Ranged_Ones"))
    print("Melee_HealSelf is flat 1.0 table:", am.is_flat_table("Melee_HealSelf"))
