"""HTML visualization helpers."""

from __future__ import annotations

import json
from datetime import datetime

from pyvis.network import Network

from ..adt_types import (
    AzureDiscoveryResponse,
    VisualizationOptions,
    VisualizationResponse,
)
from ..adt_types.errors import VisualizationError


def render_visualization(
    response: AzureDiscoveryResponse,
    options: VisualizationOptions,
) -> VisualizationResponse:
    """Render an interactive dependency graph."""

    if not response:
        raise VisualizationError("Discovery response missing")
    output_dir = options.output_dir.expanduser()
    output_dir.mkdir(parents=True, exist_ok=True)
    file_name = (
        options.file_name
        or f"azure-graph-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.html"
    )
    html_path = output_dir / file_name

    net = Network(
        height="960px",
        width="100%",
        directed=True,
        bgcolor="#05060a",
        font_color="#f5f7fa",
    )
    if options.physics_enabled:
        net.barnes_hut()
    else:
        net.force_atlas_2based(gravity=-50, central_gravity=0.015)

    for node in response.nodes:
        attributes = {
            "id": node.id,
            "type": node.type,
            "location": node.location,
            "resource_group": node.resource_group,
            "tags": node.tags,
        }
        title = json.dumps(attributes, indent=2) if options.include_attributes else node.type
        net.add_node(
            node.id,
            label=node.name,
            title=title,
            group=node.type.split("/")[-1],
        )

    for edge in response.relationships:
        net.add_edge(
            edge.source_id,
            edge.target_id,
            title=edge.relation_type,
            value=edge.weight,
        )

    try:
        net.write_html(str(html_path), notebook=False)
    except Exception as exc:  # noqa: BLE001
        raise VisualizationError("Failed to render HTML graph") from exc

    return VisualizationResponse(
        html_path=str(html_path),
        nodes=len(response.nodes),
        relationships=len(response.relationships),
    )
