"""Mermaid diagram renderer."""

from __future__ import annotations

from ..models import InfraDiagram


def render_mermaid(diagram: InfraDiagram, direction: str = "TB") -> str:
    """Render infrastructure diagram as Mermaid syntax.

    Args:
        diagram: The infrastructure diagram to render.
        direction: Flow direction — TB (top-bottom), LR (left-right), BT, RL.
    """
    lines = [f"graph {direction}"]

    # Track which nodes are in groups
    grouped_nodes: set[str] = set()
    for group in diagram.groups:
        grouped_nodes.update(group.node_ids)

    # Render groups as subgraphs
    for group in diagram.groups:
        lines.append(f"    subgraph {group.id}[\"{group.name}\"]")
        for node_id in group.node_ids:
            node = diagram.get_node(node_id)
            if node:
                lines.append(f"        {node.safe_id}[\"{node.label}\"]")
        lines.append("    end")

    # Render ungrouped nodes
    for node in diagram.nodes:
        if node.id not in grouped_nodes:
            lines.append(f"    {node.safe_id}[\"{node.label}\"]")

    # Render edges
    for edge in diagram.edges:
        src_node = diagram.get_node(edge.source)
        tgt_node = diagram.get_node(edge.target)
        if src_node and tgt_node:
            if edge.label:
                lines.append(f"    {src_node.safe_id} -->|{edge.label}| {tgt_node.safe_id}")
            else:
                lines.append(f"    {src_node.safe_id} --> {tgt_node.safe_id}")

    # Style nodes by type
    _add_styles(lines, diagram)

    return "\n".join(lines)


def _add_styles(lines: list[str], diagram: InfraDiagram) -> None:
    """Add Mermaid styling for different node types."""
    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",
    }

    for node in diagram.nodes:
        color = type_colors.get(node.node_type.value)
        if color:
            lines.append(f"    style {node.safe_id} fill:{color},color:#fff,stroke:{color}")
