import requests
import re

URL = "https://raw.githubusercontent.com/smogon/pokemon-showdown/master/data/pokedex.ts"
OUTPUT_FILE = r"c:\Users\lftam\.gemini\antigravity\scratch\Liga Tsuru\ligatsuru\anatomia\analisis_report.html"

# --- V4 LOGIC: AREA MAPPING (Type 1) ---
AREA_RULES = {
    'Normal':   'Medio',
    'Fire':     'Ataque',
    'Water':    'Medio',
    'Grass':    'Defensa',
    'Electric': 'Ataque',
    'Ice':      'Medio',
    'Fighting': 'Defensa',
    'Poison':   'Medio',
    'Ground':   'Defensa',
    'Flying':   'Ataque', # Changed to Attack (Wingers)
    'Psychic':  'Medio',  # Changed to Midfield (Playmakers), Goalkeepers are just Defense
    'Bug':      'Defensa', # Changed to Defense (pests/persistent)
    'Rock':     'Defensa',
    'Ghost':    'Ataque',
    'Dragon':   'Ataque',
    'Steel':    'Defensa',
    'Dark':     'Ataque',
    'Fairy':    'Medio',
}

# --- V4 LOGIC: LORE API (Type 2, Sum=5) ---
# Int / Con / Tec
API_LORE = {
    'Normal':   (1, 2, 2), # Balanced
    'Fighting': (0, 5, 0), # Pure Physical
    'Flying':   (0, 1, 4), # Fast/Technical
    'Poison':   (2, 2, 1), # Tricky but resilient
    'Ground':   (0, 4, 1), # Tough
    'Rock':     (0, 3, 2), # Hard but raw
    'Bug':      (1, 3, 1), # Survivor
    'Ghost':    (4, 0, 1), # Ethereal/Smart
    'Steel':    (1, 4, 0), # Iron Wall
    'Fire':     (1, 1, 3), # Explosive Technique
    'Water':    (2, 1, 2), # Fluid
    'Grass':    (1, 3, 1), # Growth/Stamina (Repeated with Bug? Let's fix uniqueness)
    'Electric': (2, 0, 3), # High Tech/Speed
    'Psychic':  (5, 0, 0), # Pure Intellect
    'Ice':      (2, 0, 3), # Cold Calc (Repeated with Elec? Fix) -> (3,0,2)
    'Dragon':   (2, 2, 1), # Strong all round (Repeated with Poison? Fix) -> (3,1,1)
    'Dark':     (3, 1, 1), # Cunning (Repeated with Dragon? Fix) -> (4,1,0)
    'Fairy':    (2, 0, 3), # Repeated with Elec? Fix -> (1, 0, 4) - Magic Tech
    'None':     (1, 2, 2)  # Balanced (Repeated with Normal? Fix) -> Normal=(2,2,1)? 
}

# Let's ensure Uniqueness Programmatically to satisfy the constraint
# We have 19 types.
# Priority List based on Lore
FINAL_API_MAP = {
    'Psychic':  (5, 0, 0), # Geniuses
    'Fighting': (0, 5, 0), # Pure Muscle
    'Fairy':    (0, 0, 5), # Pure Magic/Tech
    'Steel':    (1, 4, 0), # Iron Defense
    'electric': (1, 0, 4), # High Speed/Tech (Lower case key fix logic below)
    'Ghost':    (4, 1, 0), # Tricky
    'Rock':     (0, 4, 1), # Hard
    'Flying':   (0, 1, 4), # Aerial Tech
    'Dark':     (4, 0, 1), # Schemers
    'Ground':   (1, 3, 1), # Balanced Tank - Fixed to sum 5 -> (1,3,1)
    'Bug':      (1, 4, 0), # Repeated with Steel? -> (0, 3, 2)
    'Poison':   (3, 2, 0), # Toxic Tactics
    'Fire':     (2, 0, 3), # Offensive Tech
    'Ice':      (3, 0, 2), # Cold Calculation
    'Water':    (2, 2, 1), # Flow
    'Grass':    (1, 2, 2), # Natural structure
    'Dragon':   (2, 1, 2), # Powerful
    'Normal':   (2, 2, 1), # Variable -> Repeated w Water? -> (1,2,2) Repeated w Grass? -> (2,1,2) Repeated w Dragon? -> (3,1,1)
    'None':     (2, 2, 1)  # Base -> Repeated?
}

# Re-doing the manual mapping to GUARANTEE uniqueness for 19 slots from the generated pool
# 5 points combos:
# (5,0,0) (0,5,0) (0,0,5)
# (4,1,0) (4,0,1) (1,4,0) (0,4,1) (1,0,4) (0,1,4)
# (3,2,0) (3,0,2) (2,3,0) (0,3,2) (2,0,3) (0,2,3)
# (3,1,1) (1,3,1) (1,1,3)
# (2,2,1) (2,1,2) (1,2,2)
# Total = 21 unique tuples. We need 19.

UNIQUE_ASSIGNMENTS = {
    'Psychic':  (5, 0, 0), # Max INT
    'Fighting': (0, 5, 0), # Max CON
    'Electric': (0, 0, 5), # Max TEC (Speed)
    
    'Ghost':    (4, 1, 0), # High Int, some con
    'Steel':    (1, 4, 0), # High Con, some int
    'Flying':   (1, 0, 4), # High Tec, some int
    
    'Dark':     (4, 0, 1), # High Int, some tec
    'Rock':     (0, 4, 1), # High Con, some tec
    'Fairy':    (0, 1, 4), # High Tec, some con
    
    'Poison':   (3, 2, 0), # Smart & tough
    'Bug':      (2, 3, 0), # Tough & smart (Hive mind)
    'Ground':   (0, 3, 2), # Tough & skilled
    
    'Ice':      (3, 0, 2), # Smart & skilled
    'Fire':     (2, 0, 3), # Skilled & smart
    'Normal':   (0, 2, 3), # Efficient
    
    'Dragon':   (3, 1, 1), # Dominant
    'Grass':    (1, 3, 1), # Persistent
    'Water':    (1, 1, 3), # Fluid
    
    'None':     (2, 2, 1), # Balanced Base
}
# Unused: (2,1,2), (1,2,2)

def main():
    print(f"Downloading {URL}...")
    try:
        response = requests.get(URL)
        response.raise_for_status()
        content = response.text
    except Exception as e:
        print(f"Error downloading: {e}")
        return

    print("Parsing content...")
    entries = [] 
    
    chunks = content.split("},\n\t")
    
    for chunk in chunks:
        # Extract Num
        num_match = re.search(r'num:\s*(\d+)', chunk)
        if not num_match: continue
        num = int(num_match.group(1))
        
        if num <= 0: continue
        if "baseSpecies:" in chunk: continue
        
        # Extract Name
        name_match = re.search(r'name:\s*"([^"]+)"', chunk)
        if not name_match: continue
        name = name_match.group(1)
        
        # Extract Types
        types_match = re.search(r'types:\s*\[([^\]]+)\]', chunk)
        if not types_match: continue
        types_str = types_match.group(1)
        # Clean quotes
        types = [t.strip().strip('"').strip("'") for t in types_str.split(",")]
        
        t1 = types[0]
        t2 = types[1] if len(types) > 1 else "None"
        
        entries.append({'name': name, 't1': t1, 't2': t2})

    print(f"Parsed {len(entries)} Pokemon.")
    
    # --- ANALYSIS ---
    area_counts = {'Defensa': 0, 'Medio': 0, 'Ataque': 0}
    type_details = [] # List of dicts for the big table
    
    for p in entries:
        t1 = p['t1']
        t2 = p['t2']
        
        # Area (Type 1)
        area = AREA_RULES.get(t1, 'Medio')
        area_counts[area] += 1
        
        # API (Type 2)
        api = UNIQUE_ASSIGNMENTS.get(t2, (2,2,1))
        
        type_details.append({
            'num': p.get('num', 0), # We didn't store num in entries list above, let's just ignore or fix if needed. 
            'name': p['name'],
            't1': t1,
            't2': t2,
            'area': area,
            'api': api
        })
        
    # --- HTML GENERATION ---
    html = f"""
    <!DOCTYPE html>
    <html lang="es">
    <head>
        <meta charset="UTF-8">
        <title>Reporte V4: Lore & Sorting</title>
        <style>
            body {{ font-family: 'Segoe UI', sans-serif; background: #f4f6f8; padding: 20px; }}
            h1, h2 {{ color: #2c3e50; }}
            .card {{ background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); margin-bottom: 20px; }}
            table {{ width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 0.9rem; }}
            th, td {{ padding: 8px 12px; text-align: left; border-bottom: 1px solid #ddd; cursor: pointer; }}
            th {{ background: #ecf0f1; position: sticky; top: 0; }}
            th:hover {{ background: #dce4e6; }}
            .badge {{ display: inline-block; padding: 3px 6px; border-radius: 4px; color: white; font-size: 0.8em; font-weight: bold; min-width: 60px; text-align: center; }}
            
            .type-Normal {{ background: #A8A77A; }}
            .type-Fire {{ background: #EE8130; }}
            .type-Water {{ background: #6390F0; }}
            .type-Electric {{ background: #F7D02C; color: #333; }}
            .type-Grass {{ background: #7AC74C; }}
            .type-Ice {{ background: #96D9D6; }}
            .type-Fighting {{ background: #C22E28; }}
            .type-Poison {{ background: #A33EA1; }}
            .type-Ground {{ background: #E2BF65; }}
            .type-Flying {{ background: #A98FF3; }}
            .type-Psychic {{ background: #F95587; }}
            .type-Bug {{ background: #A6B91A; }}
            .type-Rock {{ background: #B6A136; }}
            .type-Ghost {{ background: #735797; }}
            .type-Dragon {{ background: #6F35FC; }}
            .type-Dark {{ background: #705746; }}
            .type-Steel {{ background: #B7B7CE; }}
            .type-Fairy {{ background: #D685AD; }}
            .type-None {{ background: #999; }}
            
            .cols {{ display: flex; gap: 20px; }}
            .col {{ flex: 1; }}
        </style>
        <script>
            function sortTable(n, tableId) {{
              var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
              table = document.getElementById(tableId);
              switching = true;
              dir = "asc"; 
              while (switching) {{
                switching = false;
                rows = table.rows;
                for (i = 1; i < (rows.length - 1); i++) {{
                  shouldSwitch = false;
                  x = rows[i].getElementsByTagName("TD")[n];
                  y = rows[i + 1].getElementsByTagName("TD")[n];
                  var xContent = x.textContent.toLowerCase();
                  var yContent = y.textContent.toLowerCase();
                  // Check if numeric
                  if (!isNaN(parseFloat(xContent)) && isFinite(xContent)) {{
                      xContent = parseFloat(xContent);
                      yContent = parseFloat(yContent);
                  }}
                  
                  if (dir == "asc") {{
                    if (xContent > yContent) {{ shouldSwitch = true; break; }}
                  }} else if (dir == "desc") {{
                    if (xContent < yContent) {{ shouldSwitch = true; break; }}
                  }}
                }}
                if (shouldSwitch) {{
                  rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                  switching = true;
                  switchcount ++;      
                }} else {{
                  if (switchcount == 0 && dir == "asc") {{
                    dir = "desc";
                    switching = true;
                  }}
                }}
              }}
            }}
        </script>
    </head>
    <body>
        <h1>Reporte V4: Lore de 5 Puntos & Ordenamiento</h1>
        
        <div class="cols">
            <div class="col">
                <div class="card">
                    <h2>1. Distribución de Áreas (V4)</h2>
                    <p>Defensa puede ser Portero.</p>
                    <table id="areaTable">
                        <thead>
                            <tr>
                                <th onclick="sortTable(0, 'areaTable')">Área &#8645;</th>
                                <th onclick="sortTable(1, 'areaTable')">Cantidad &#8645;</th>
                                <th onclick="sortTable(2, 'areaTable')">% &#8645;</th>
                            </tr>
                        </thead>
                        <tbody>
    """
    total = len(entries)
    for area, count in area_counts.items():
        pct = round((count / total) * 100, 1)
        html += f"""<tr>
            <td>{area}</td>
            <td>{count}</td>
            <td>{pct}%</td>
        </tr>"""
        
    html += """     </tbody>
                    </table>
                </div>
            </div>
            
             <div class="col">
                <div class="card">
                    <h2>2. Grilla de API por Lore (Combinaciones Únicas)</h2>
                    <p>Cada Tipo tiene su propia identidad (Suma=5).</p>
                    <table id="apiTable">
                        <thead>
                            <tr>
                                <th onclick="sortTable(0, 'apiTable')">Tipo 2 &#8645;</th>
                                <th onclick="sortTable(1, 'apiTable')">I (Int) &#8645;</th>
                                <th onclick="sortTable(2, 'apiTable')">C (Con) &#8645;</th>
                                <th onclick="sortTable(3, 'apiTable')">T (Tec) &#8645;</th>
                            </tr>
                        </thead>
                        <tbody>
    """
    for t, v in UNIQUE_ASSIGNMENTS.items():
        html += f"""<tr>
            <td><span class="badge type-{t}">{t}</span></td>
            <td>{v[0]}</td>
            <td>{v[1]}</td>
            <td>{v[2]}</td>
        </tr>"""
        
    html += """     </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <div class="card">
            <h2>3. Mapeo Completo</h2>
            <p>Haz clic en los encabezados para ordenar.</p>
             <table id="mainTable">
                <thead>
                    <tr>
                        <th onclick="sortTable(0, 'mainTable')">Nombre &#8645;</th>
                        <th onclick="sortTable(1, 'mainTable')">Tipo 1 (Área) &#8645;</th>
                        <th onclick="sortTable(2, 'mainTable')">Área Asignada &#8645;</th>
                        <th onclick="sortTable(3, 'mainTable')">Tipo 2 (API) &#8645;</th>
                        <th onclick="sortTable(4, 'mainTable')">API (I/C/T) &#8645;</th>
                    </tr>
                </thead>
                <tbody>
    """
    for row in type_details:
        api_str = f"{row['api'][0]} / {row['api'][1]} / {row['api'][2]}"
        html += f"""<tr>
            <td>{row['name']}</td>
            <td><span class="badge type-{row['t1']}">{row['t1']}</span></td>
            <td><strong>{row['area']}</strong></td>
            <td><span class="badge type-{row['t2']}">{row['t2']}</span></td>
            <td>{api_str}</td>
        </tr>"""

    html += """
                </tbody>
            </table>
        </div>
    </body>
    </html>
    """
    
    with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
        f.write(html)
        
    print(f"Done. Report at {OUTPUT_FILE}")

if __name__ == "__main__":
    main()
