"""Affiche le plan d'insertion pour les 3 entrées de test."""
import sys, csv, json, re
sys.stdout.reconfigure(encoding="utf-8")
from pathlib import Path

D = Path(r"c:\wamp64\www\csi-world\csv_data\csi-forever")

MAP_ELEMENT = {1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:15,10:11,11:9,12:17}
MAP_WTYPE   = {1:1,2:2,3:3,4:4,5:5,6:6,8:7,9:14,19:8,20:9,21:10,22:11,24:12}
MAP_ATYPE   = {1:2,2:4,3:1,4:3,5:5,6:6,7:7}

XPARAM = {0:"accuracy",1:"evasion",2:"criticalRate",3:"criticalEvasion",4:"magicEvasion",
          6:"physicalCounter",7:"regenPv",8:"regenEg",9:"regenPower"}
PMULT  = {0:"multiplierPvMax",1:"multiplierEgMax",2:"multiplierAttaque",3:"multiplierDefense",
          4:"multiplierArcane",5:"multiplierSagesse",6:"multiplierVitesse",7:"multiplierFinesse"}

CLEAN_RE_C = re.compile(r"\\c\[\d+\]")
CLEAN_RE_I = re.compile(r"\\i\[\d+\]")

def clean_desc(s: str) -> str:
    s = CLEAN_RE_C.sub("", s or "")
    s = CLEAN_RE_I.sub("", s)
    return re.sub(r"\s+", " ", s).strip()

def load(name):
    with (D/name).open(encoding="utf-8-sig") as f:
        return list(csv.DictReader(f, delimiter=";"))

states  = load("States.csv")
weapons = load("Weapons.csv")
armors  = load("Armors.csv")

S95 = next(r for r in states  if r["id"]=="95")
W69 = next(r for r in weapons if r["id"]=="69")
A37 = next(r for r in armors  if r["id"]=="37")

def rarity_of(note):
    m = re.search(r"<item rarity: (\d+)>", note or "")
    return int(m.group(1)) if m else 0

print("══════ STATUS 95 : Sixième sens ══════")
print(f"  gameId          = 0")
print(f"  name            = {S95['name']}")
print(f"  icon            = {S95['icon_index']}")
print(f"  restrictionType = {S95['restriction']}")
print(f"  endsAfterBattle = {bool(int(S95['remove_at_battle_end']))}")
print(f"  endsAfterAction = {S95['auto_removal_timing']=='1'}")
print(f"  endsAfterTurn   = {S95['auto_removal_timing']=='2'}")
print(f"  minTurns/maxTurns = NULL (permastate)")
print(f"  Features → trait :")
for f in json.loads(S95["features_json"]):
    if f["code"]==22:
        col = XPARAM.get(f["data_id"])
        if col: print(f"    X-param[{f['data_id']}] → trait.{col} = {int(round(f['value']*100))} (%)")
        else:   print(f"    X-param[{f['data_id']}] (Magic Reflection) → ⚠ pas de colonne DB, ignoré")
print()

print("══════ WEAPON 69 : Étendard fantastique ══════")
print(f"  gameId          = 0")
print(f"  name            = {W69['name']}")
print(f"  icon            = {W69['icon_index']}")
print(f"  description     = {clean_desc(W69['description'])}")
print(f"  weaponTypeId    = {MAP_WTYPE[int(W69['wtype_id'])]} (cf wtype {W69['wtype_id']} = Lance)")
print(f"  value           = {W69['price']}")
print(f"  rarity          = {rarity_of(W69['note'])}")
print(f"  stats.attaque   = {W69['atk']}")
print(f"  Features → DB :")
for f in json.loads(W69["features_json"]):
    if f["code"]==31:
        e = MAP_ELEMENT.get(f["data_id"])
        print(f"    code 31 (élément attaque) → elementModifier_id = {e} (Féerique)")
    elif f["code"]==32:
        print(f"    code 32 → inflige state cf #{f['data_id']} (Défense -) @ {int(f['value']*100)}%")
        print(f"             ⚠ state non en DB → garder en specialEffect texte")
    elif f["code"]==43:
        print(f"    code 43 → grantsSkills = [{f['data_id']}]  (Corne de guerre, id rvdata brut)")
print()

print("══════ ARMOR 37 : Tête Jivaro ══════")
print(f"  gameId          = 0")
print(f"  name            = {A37['name']}")
print(f"  icon            = {A37['icon_index']}")
print(f"  description     = {clean_desc(A37['description'])}")
print(f"  armorTypeId     = {MAP_ATYPE[int(A37['atype_id'])]} (cf atype {A37['atype_id']} = Armure magique)")
print(f"  slot            = {A37['etype_id']} (2 = Helmet)")
print(f"  value           = {A37['price']}")
print(f"  rarity          = {rarity_of(A37['note'])}")
print(f"  stats.defense   = {A37['def']}")
print(f"  Features → DB :")
for f in json.loads(A37["features_json"]):
    if f["code"]==21:
        print(f"    code 21 (param rate) → trait.{PMULT[f['data_id']]} = {f['value']}")
    elif f["code"]==22:
        col = XPARAM.get(f["data_id"])
        v   = int(round(f["value"]*100))
        if col: print(f"    code 22 X-param[{f['data_id']}] → trait.{col} = {v} (%)")
