"""HTML report generator for infra-diagram — renders interactive diagram."""

from __future__ import annotations

import html as _html
from pathlib import Path

from ..models import InfraDiagram
from ..renderers.mermaid import render_mermaid


def _css() -> str:
    return """
    :root { --bg: #0f172a; --surface: #1e293b; --border: #334155; --text: #e2e8f0; --muted: #94a3b8; --accent: #3b82f6; }
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: var(--text); padding: 2rem; }
    .container { max-width: 1300px; margin: 0 auto; }
    h1 { font-size: 1.8rem; margin-bottom: .3rem; }
    h2 { font-size: 1.2rem; margin: 1.6rem 0 .7rem; color: var(--accent); }
    .subtitle { color: var(--muted); margin-bottom: 1.5rem; }
    .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: .8rem; margin-bottom: 1.5rem; }
    .card { background: var(--surface); border: 1px solid var(--border); border-radius: .75rem; padding: 1rem; text-align: center; }
    .card .value { font-size: 2rem; font-weight: 700; }
    .card .label { color: var(--muted); font-size: .8rem; margin-top: .2rem; }
    .diagram-box { background: #fff; border-radius: .75rem; padding: 2rem; margin: 1.5rem 0; min-height: 200px; }
    .mermaid { text-align: center; }
    table { width: 100%; border-collapse: collapse; margin-bottom: 1.2rem; }
    th { background: var(--surface); text-align: left; padding: .5rem .7rem; font-size: .78rem; text-transform: uppercase; color: var(--muted); border-bottom: 2px solid var(--border); }
    td { padding: .45rem .7rem; border-bottom: 1px solid var(--border); font-size: .88rem; }
    tr:hover td { background: rgba(59,130,246,.06); }
    .type-badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: .76rem; font-weight: 600; color: #fff; background: var(--accent); }
    .footer { text-align: center; color: var(--muted); font-size: .78rem; margin-top: 2rem; padding-top: 1rem; border-top: 1px solid var(--border); }
    .two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
    @media (max-width: 768px) { .two-col { grid-template-columns: 1fr; } }
    pre.mermaid-source { background: var(--surface); padding: 1rem; border-radius: .5rem; overflow-x: auto; font-size: .85rem; color: var(--muted); white-space: pre-wrap; }
    """


_TYPE_COLORS = {
    "compute": "#2563eb", "container": "#0891b2", "serverless": "#7c3aed",
    "vm": "#2563eb", "storage": "#059669", "database": "#ea580c",
    "cache": "#d97706", "queue": "#9333ea", "network": "#334155",
    "load_balancer": "#0284c7", "firewall": "#dc2626", "gateway": "#4f46e5",
    "iam": "#ca8a04", "secret": "#be123c", "monitoring": "#16a34a",
    "service": "#6366f1", "volume": "#0d9488", "ingress": "#4f46e5",
    "deployment": "#0891b2", "pod": "#0891b2", "config": "#6b7280",
    "namespace": "#334155", "unknown": "#6b7280",
}


def export_html(diagram: InfraDiagram, output_path: str) -> str:
    """Generate HTML report with Mermaid diagram."""
    mermaid_code = render_mermaid(diagram, direction="LR")

    # Summary cards
    providers = {n.provider for n in diagram.nodes if n.provider}
    types_count = len({n.node_type for n in diagram.nodes})

    cards = f"""
    <div class="cards">
        <div class="card"><div class="value">{diagram.node_count}</div><div class="label">Components</div></div>
        <div class="card"><div class="value">{diagram.edge_count}</div><div class="label">Connections</div></div>
        <div class="card"><div class="value">{types_count}</div><div class="label">Resource Types</div></div>
        <div class="card"><div class="value">{len(providers)}</div><div class="label">Providers</div></div>
        <div class="card"><div class="value">{len(diagram.groups)}</div><div class="label">Groups</div></div>
        <div class="card"><div class="value">{len(diagram.source_files)}</div><div class="label">Source Files</div></div>
    </div>
    """

    # Mermaid diagram
    diagram_html = f"""
    <h2>Architecture Diagram</h2>
    <div class="diagram-box">
        <div class="mermaid">{_html.escape(mermaid_code)}</div>
    </div>
    """

    # Components table
    comp_rows = ""
    for i, node in enumerate(diagram.nodes, 1):
        color = _TYPE_COLORS.get(node.node_type.value, "#6b7280")
        comp_rows += f"""<tr>
            <td>{i}</td>
            <td>{node.icon}</td>
            <td><b>{_html.escape(node.name)}</b></td>
            <td><span class="type-badge" style="background:{color}">{node.node_type.value}</span></td>
            <td>{_html.escape(node.provider)}</td>
        </tr>"""

    components_html = f"""
    <h2>Components</h2>
    <table>
        <thead><tr><th>#</th><th></th><th>Name</th><th>Type</th><th>Provider</th></tr></thead>
        <tbody>{comp_rows}</tbody>
    </table>
    """

    # Connections table
    conn_rows = ""
    for edge in diagram.edges:
        src = diagram.get_node(edge.source)
        tgt = diagram.get_node(edge.target)
        if src and tgt:
            conn_rows += f"""<tr>
                <td>{_html.escape(src.name)}</td>
                <td style="text-align:center">→</td>
                <td>{_html.escape(tgt.name)}</td>
                <td>{_html.escape(edge.label)}</td>
            </tr>"""

    connections_html = ""
    if conn_rows:
        connections_html = f"""
        <h2>Connections</h2>
        <table>
            <thead><tr><th>From</th><th></th><th>To</th><th>Relation</th></tr></thead>
            <tbody>{conn_rows}</tbody>
        </table>
        """

    # Mermaid source
    source_html = f"""
    <h2>Mermaid Source</h2>
    <pre class="mermaid-source">{_html.escape(mermaid_code)}</pre>
    <p style="color:var(--muted);font-size:.8rem;margin-top:.5rem;">
        Copy the code above into <a href="https://mermaid.live" style="color:var(--accent)">mermaid.live</a> for interactive editing.
    </p>
    """

    page = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <title>infra-diagram · {_html.escape(diagram.title)}</title>
    <style>{_css()}</style>
    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <script>mermaid.initialize({{startOnLoad:true, theme:'default'}});</script>
</head>
<body>
<div class="container">
    <h1>🏗️ infra-diagram</h1>
    <p class="subtitle">{_html.escape(diagram.title)} · {diagram.source_type.value}</p>
    {cards}
    {diagram_html}
    <div class="two-col">
        <div>{components_html}</div>
        <div>{connections_html}</div>
    </div>
    {source_html}
    <div class="footer">Generated by infra-diagram · Infrastructure Diagram Generator</div>
</div>
</body>
</html>"""

    Path(output_path).parent.mkdir(parents=True, exist_ok=True)
    Path(output_path).write_text(page, encoding="utf-8")
    return output_path
