#!/usr/bin/env python3
"""
Genera un cap-team dashboard a partir del template y un JSON de datos.
Uso: python3 generate_dashboard.py <datos.json> <output.html>

El JSON debe tener esta estructura:
{
  "title": "Team Capacity Dashboard",
  "subtitle": "PMO — SWFactory × La Punta del Iceberg",
  "date": "2026-03-08",
  "week": "Semana 1",
  "last_updated": "2026-03-08 · 14:35",
  "summary": [
    {"label": "Proyectos Activos", "value": "3", "detail": "2 activos · 1 pendiente", "color": "cyan"},
    {"label": "Tareas Totales", "value": "0/6", "detail": "6 pendientes", "color": "green"},
    {"label": "Proyecto Foco", "value": "bm-web-v2", "detail": "MVP · 0/6 módulos", "color": "amber"},
    {"label": "Decisiones Pendientes", "value": "4", "detail": "Requieren decisión", "color": "violet"}
  ],
  "agents": [
    {
      "id": "pmo",
      "emoji": "📋",
      "name": "PMO Agent",
      "role": "Coordinando 2 proyectos",
      "pct": 75,
      "bar_colors": ["#06b6d4", "#0891b2"],
      "status": "ACTIVO",
      "status_color": "#10b981",
      "activities": [
        {"icon": "📊", "text": "Dashboard de capacidad", "project": "agents-pmo", "status": "en curso", "status_color": "#06b6d4"},
        {"icon": "📐", "text": "Gestión de alcance", "project": "bm-web-v2", "status": "esperando", "status_color": "#f59e0b"}
      ]
    }
  ],
  "projects": [
    {
      "name": "Basic Memory Web v2",
      "client": "Roberto (interno) · SvelteKit",
      "tasks": "0/6",
      "phase": "MVP",
      "phase_color": "#f59e0b",
      "dot_color": "#06b6d4"
    }
  ],
  "modules": {
    "title": "Basic Memory Web v2 — Módulos MVP",
    "items": [
      {"id": "M1", "name": "Setup SvelteKit + shadcn", "effort": "1d", "status": "pendiente"}
    ]
  },
  "decisions": [
    {"icon": "📝", "text": "Editor: textarea vs rich editor", "owner": "Roberto", "urgency": "ANTES M5", "urgency_color": "#f59e0b"}
  ],
  "risks": [
    {"text": "CLI puede cambiar interfaz JSON", "mitigation": "Bridge centraliza", "color": "#f59e0b"}
  ],
  "timeline": [
    {"date": "Mar 8", "label": "Alcance definido", "detail": "Stack, contratos, módulos", "state": "done"},
    {"date": "Día 0", "label": "Contratos de integración", "detail": "Prerequisito", "state": "active"},
    {"date": "Días 1-3", "label": "M1 + M2", "detail": "Backend funcional", "state": "pending"}
  ],
  "footer": "PMO Agent · Datos reales de basic-memory"
}
"""

import json
import sys
import os

def status_class(status: str) -> str:
    s = status.lower()
    if s in ("completado", "completada", "done", "entregado"):
        return "status-done"
    if s in ("en progreso", "en curso", "progress"):
        return "status-progress"
    if s in ("bloqueado", "bloqueada", "blocked"):
        return "status-blocked"
    return "status-pending"


def generate(data: dict) -> str:
    template_path = os.path.join(os.path.dirname(__file__), "cap-team-template.html")
    with open(template_path) as f:
        template = f.read()

    # Extract CSS and JS from template (everything between <style> and </style>, <script> and </script>)
    import re
    style_match = re.search(r'<style>(.*?)</style>', template, re.DOTALL)
    script_match = re.search(r'<script>(.*?)</script>', template, re.DOTALL)
    css = style_match.group(1) if style_match else ""
    js = script_match.group(1) if script_match else ""

    # Build summary cards
    summary_html = ""
    for card in data.get("summary", []):
        summary_html += f'''
        <div class="summary-card {card['color']}">
            <div class="label">{card['label']}</div>
            <div class="value">{card['value']}</div>
            <div class="detail">{card['detail']}</div>
        </div>'''

    # Build agent rows
    agents_html = ""
    for agent in data.get("agents", []):
        activities_html = ""
        for act in agent.get("activities", []):
            activities_html += f'''
                    <div class="activity-item">
                        <span class="activity-icon">{act['icon']}</span>
                        <span class="activity-text">{act['text']}</span>
                        <span class="activity-project">{act['project']}</span>
                        <span class="activity-status-tag" style="background: rgba({_hex_to_rgb(act.get('status_color', '#06b6d4'))}, 0.2); color: {act.get('status_color', '#06b6d4')};">{act['status']}</span>
                    </div>'''

        available_pct = 100 - agent['pct']
        agents_html += f'''
            <div class="agent-row" onclick="toggleDrilldown('{agent['id']}')">
                <span class="expand-icon">▶</span>
                <div class="agent-avatar">{agent['emoji']}</div>
                <div class="agent-info">
                    <div class="agent-name">{agent['name']}</div>
                    <div class="agent-role">{agent['role']}</div>
                </div>
                <div>
                    <div class="agent-bar-bg">
                        <div class="agent-bar-fill" style="width: {available_pct}%; background: linear-gradient(90deg, {agent['bar_colors'][0]}, {agent['bar_colors'][1]});"></div>
                    </div>
                </div>
                <span class="agent-pct">{available_pct}%</span>
                <span class="agent-status" style="background: rgba({_hex_to_rgb(agent['status_color'])}, 0.2); color: {agent['status_color']};">{agent['status']}</span>
            </div>
            <div class="agent-drilldown" id="drilldown-{agent['id']}">
                <div class="agent-drilldown-inner">
                    <div class="drilldown-header">Actividades actuales</div>
                    {activities_html}
                </div>
            </div>'''

    # Build projects
    projects_html = ""
    for proj in data.get("projects", []):
        projects_html += f'''
            <div class="project-item">
                <div class="project-dot" style="background: {proj['dot_color']};"></div>
                <div class="project-info">
                    <div class="project-name">{proj['name']}</div>
                    <div class="project-client">{proj['client']}</div>
                </div>
                <div class="project-tasks">{proj['tasks']}</div>
                <span class="project-phase" style="background: rgba({_hex_to_rgb(proj['phase_color'])}, 0.2); color: {proj['phase_color']};">{proj['phase']}</span>
            </div>'''

    # Build modules
    modules_section = ""
    modules = data.get("modules")
    if modules and modules.get("items"):
        modules_rows = ""
        for mod in modules["items"]:
            sc = status_class(mod["status"])
            modules_rows += f'''
                <div class="module-row">
                    <span class="module-id">{mod['id']}</span>
                    <span class="module-name">{mod['name']}</span>
                    <span class="module-effort">{mod['effort']}</span>
                    <span class="module-status {sc}">{mod['status']}</span>
                </div>'''
        modules_section = f'''
    <div class="panel full-width">
        <div class="panel-title">
            <span class="dot" style="background: #f59e0b;"></span>
            {modules['title']}
        </div>
        <div class="module-grid">{modules_rows}
        </div>
    </div>'''

    # Build decisions
    decisions_html = ""
    for dec in data.get("decisions", []):
        decisions_html += f'''
            <div class="decision-row">
                <span class="decision-icon">{dec['icon']}</span>
                <span class="decision-text">{dec['text']}</span>
                <div style="flex: 0 0 auto; display: flex; gap: 10px; align-items: center;">
                    <span class="decision-owner">{dec['owner']}</span>
                    <span class="decision-urgency" style="background: rgba({_hex_to_rgb(dec.get('urgency_color', '#f59e0b'))}, 0.2); color: {dec.get('urgency_color', '#f59e0b')};">{dec['urgency']}</span>
                </div>
            </div>'''

    # Build risks
    risks_html = ""
    for risk in data.get("risks", []):
        risks_html += f'''
            <div class="risk-row">
                <span class="risk-indicator" style="background: {risk.get('color', '#f59e0b')};"></span>
                <span class="risk-text">{risk['text']}</span>
                <span class="risk-mitigation">{risk['mitigation']}</span>
            </div>'''

    # Build timeline
    timeline_html = ""
    for item in data.get("timeline", []):
        state_class = item.get("state", "pending")
        if state_class == "done":
            cls = "done"
        elif state_class == "active":
            cls = "active"
        else:
            cls = ""
        timeline_html += f'''
            <div class="timeline-item {cls}">
                <div class="timeline-date">{item['date']}</div>
                <div class="timeline-label">{item['label']}</div>
                <div class="timeline-detail">{item['detail']}</div>
            </div>'''

    # Assemble
    html = f'''<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{data.get('title', 'Team Capacity Dashboard')} — PMO</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;600;700&family=JetBrains+Mono:wght@400;600;700&display=swap" rel="stylesheet">
    <style>{css}</style>
</head>
<body>
    <div class="header">
        <div>
            <h1>⚡ {data.get('title', 'Team Capacity Dashboard')}</h1>
            <p class="subtitle">{data.get('subtitle', '')}</p>
        </div>
        <div>
            <div class="date-badge">{data.get('date', '')} · {data.get('week', '')}</div>
            <div class="last-updated">Última actualización: {data.get('last_updated', '')}</div>
        </div>
    </div>

    <div class="summary-grid">{summary_html}
    </div>

    <div class="main-grid">
        <div class="panel">
            <div class="panel-title">
                <span class="dot" style="background: #06b6d4;"></span>
                Carga por Agente
            </div>
            {agents_html}
        </div>

        <div class="panel">
            <div class="panel-title">
                <span class="dot" style="background: #10b981;"></span>
                Proyectos
            </div>
            {projects_html}
        </div>
    </div>

    {modules_section}

    <div class="main-grid">
        <div class="panel">
            <div class="panel-title">
                <span class="dot" style="background: #f43f5e;"></span>
                Decisiones Pendientes
            </div>
            {decisions_html}
        </div>

        <div class="panel">
            <div class="panel-title">
                <span class="dot" style="background: #f59e0b;"></span>
                Riesgos Activos
            </div>
            {risks_html}
        </div>
    </div>

    <div class="panel full-width">
        <div class="panel-title">
            <span class="dot" style="background: #06b6d4;"></span>
            Timeline
        </div>
        <div class="timeline-container">{timeline_html}
        </div>
    </div>

    <div style="text-align: center; margin-top: 32px; color: var(--text-muted); font-size: 11px;">
        {data.get('footer', '')}
    </div>

    <script>{js}</script>
</body>
</html>'''

    return html


def _hex_to_rgb(hex_color: str) -> str:
    """Convert #RRGGBB to R, G, B string."""
    h = hex_color.lstrip('#')
    if len(h) != 6:
        return "100, 100, 100"
    return f"{int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}"


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print(f"Uso: {sys.argv[0]} <datos.json> <output.html>")
        sys.exit(1)

    with open(sys.argv[1]) as f:
        data = json.load(f)

    html = generate(data)

    with open(sys.argv[2], "w") as f:
        f.write(html)

    print(f"Dashboard generado: {sys.argv[2]} ({len(html)} bytes)")
