def convertir_base_datos(fichero_entrada, fichero_salida):
    # Mapping for EV stats
    stat_names = ["HP", "ATTACK", "DEFENSE", "SPEED", "SPATTACK", "SPDEF"]
    
    # Limpiar el archivo de salida antes de escribir
    with open(fichero_salida, "w", encoding="utf-8") as f_out:
        f_out.write("")
    
    datos_pokemon = {}
    with open(fichero_entrada, "r", encoding="utf-8") as archivo:
        for linea in archivo:
            linea = linea.strip()
            if not linea or linea.startswith("#"):
                continue  # Saltar líneas vacías o comentarios
            if linea.startswith("[") and linea.endswith("]"):
                # Si ya hay una entrada previa, escribirla
                if datos_pokemon:
                    escribir_datos(datos_pokemon, fichero_salida, stat_names)
                    datos_pokemon.clear()
                datos_pokemon["InternalName"] = linea[1:-1]
            else:
                if "=" in linea:
                    clave, valor = linea.split("=", 1)
                    datos_pokemon[clave.strip()] = valor.strip()
        # Escribir la última entrada
        if datos_pokemon:
            escribir_datos(datos_pokemon, fichero_salida, stat_names)

def escribir_datos(datos, fichero_salida, stat_names):
    # Preparar campos
    internal = datos.get("InternalName", "")
    name = datos.get("Name", "")
    
    type1 = datos.get("Type1", "")
    type2 = datos.get("Type2", "")
    types = type1 if not type2 else f"{type1},{type2}"
    
    base_stats = datos.get("BaseStats", "")
    gender = datos.get("GenderRate", "")
    growth = datos.get("GrowthRate", "")
    base_exp = datos.get("BaseEXP", "")
    
    # Calcular EVs a partir de EffortPoints
    ev_string = ""
    if "EffortPoints" in datos:
        ev_parts = datos["EffortPoints"].split(",")
        evs = []
        for i, val in enumerate(ev_parts):
            try:
                points = int(val)
            except ValueError:
                points = 0
            if points > 0:
                evs.append(f"{stat_names[i]},{points}")
        ev_string = "/".join(evs) if evs else ""
    if not ev_string:
        ev_string = "HP,1"  # Valor por defecto si no hay EVs definidos
    
    catch_rate = datos.get("Rareness", "")
    happiness = datos.get("Happiness", "")
    
    abilities = datos.get("Abilities", "")
    hidden = datos.get("HiddenAbility", "")
    
    moves = datos.get("Moves", "")
    tutor = datos.get("TutorMoves", "")
    egg_moves = datos.get("EggMoves", "")
    
    egg_groups = datos.get("Compatibility", "")
    hatch = datos.get("StepsToHatch", "")
    
    height = datos.get("Height", "")
    weight = datos.get("Weight", "")
    color = datos.get("Color", "")
    shape = datos.get("Shape", "")
    habitat = datos.get("Habitat", "")
    category = datos.get("Kind", "")
    pokedex = datos.get("Pokedex", "")
    
    generation = datos.get("Generation", "1")
    evolutions = datos.get("Evolutions", "")
    
    # Escribir en fichero de salida
    with open(fichero_salida, "a", encoding="utf-8") as archivo:
        archivo.write("#-------------------------------\n")
        archivo.write(f"[{internal}]\n")
        archivo.write(f"Name = {name}\n")
        archivo.write(f"Types = {types}\n")
        archivo.write(f"BaseStats = {base_stats}\n")
        archivo.write(f"GenderRatio = {gender}\n")
        archivo.write(f"GrowthRate = {growth}\n")
        archivo.write(f"BaseExp = {base_exp}\n")
        archivo.write(f"EVs = {ev_string}\n")
        archivo.write(f"CatchRate = {catch_rate}\n")
        archivo.write(f"Happiness = {happiness}\n")
        archivo.write(f"Abilities = {abilities}\n")
        archivo.write(f"HiddenAbilities = {hidden}\n")
        archivo.write(f"Moves = {moves}\n")
        archivo.write(f"TutorMoves = {tutor}\n")
        archivo.write(f"EggMoves = {egg_moves}\n")
        archivo.write(f"EggGroups = {egg_groups}\n")
        archivo.write(f"HatchSteps = {hatch}\n")
        archivo.write(f"Height = {height}\n")
        archivo.write(f"Weight = {weight}\n")
        archivo.write(f"Color = {color}\n")
        archivo.write(f"Shape = {shape}\n")
        archivo.write(f"Habitat = {habitat}\n")
        archivo.write(f"Category = {category}\n")
        archivo.write(f"Pokedex = {pokedex}\n")
        archivo.write(f"Generation = {generation}\n")
        archivo.write(f"Evolutions = {evolutions}\n\n")

# Rutas específicas del usuario
ruta_entrada = r"D:\Pokemon_Armonia\PBS\pokemon.txt"
ruta_salida  = r"D:\Github\Test-Cuantico\Graphics\Pokemon\Future additions\pbs.txt"

# Llamada a la función con las rutas indicadas
convertir_base_datos(ruta_entrada, ruta_salida)

print(f"¡Conversión completada!\nDatos tomados de: {ruta_entrada}\nGuardados en: {ruta_salida}")
