"""Tests for HTML visualization helpers."""

from __future__ import annotations

from pathlib import Path
from typing import Any

import pytest

from azure_discovery.adt_types import (
    AzureDiscoveryResponse,
    ResourceNode,
    VisualizationOptions,
)
from azure_discovery.adt_types.errors import VisualizationError
from azure_discovery.reporting import html as html_module


class DummyNetwork:
    def __init__(self, *args: Any, **kwargs: Any) -> None:
        self.nodes: list[dict[str, Any]] = []
        self.edges: list[dict[str, Any]] = []
        self.physics_mode = None

    def barnes_hut(self) -> None:
        self.physics_mode = "barnes_hut"

    def force_atlas_2based(self, **_: Any) -> None:
        self.physics_mode = "force_atlas_2based"

    def add_node(self, node_id: str, **attributes: Any) -> None:
        self.nodes.append({"id": node_id, **attributes})

    def add_edge(self, source: str, target: str, **attributes: Any) -> None:
        self.edges.append({"source": source, "target": target, **attributes})

    def write_html(self, path: str, notebook: bool = False) -> None:  # noqa: FBT001, FBT002
        Path(path).write_text("<html></html>", encoding="utf-8")


def _build_response() -> AzureDiscoveryResponse:
    nodes = [
        ResourceNode(
            id="vm-a",
            name="vm-a",
            type="Microsoft.Compute/virtualMachines",
            subscription_id="sub-a",
            dependencies=["nic-b"],
        ),
        ResourceNode(
            id="nic-b",
            name="nic-b",
            type="Microsoft.Network/networkInterfaces",
            subscription_id="sub-a",
        ),
    ]
    return AzureDiscoveryResponse(
        tenant_id="tenant-1",
        discovered_subscriptions=["sub-a"],
        nodes=nodes,
        relationships=[],
        total_resources=len(nodes),
    )


def test_render_visualization_writes_html(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    response = _build_response()
    options = VisualizationOptions(
        output_dir=tmp_path,
        file_name="graph.html",
        include_attributes=False,
        physics_enabled=False,
    )
    monkeypatch.setattr(html_module, "Network", DummyNetwork)

    visualization = html_module.render_visualization(response, options)

    output_path = tmp_path / "graph.html"
    assert output_path.is_file()
    assert visualization.html_path == str(output_path)
    assert visualization.nodes == len(response.nodes)
    assert visualization.relationships == len(response.relationships)


def test_render_visualization_rejects_missing_response() -> None:
    options = VisualizationOptions()

    with pytest.raises(VisualizationError):
        html_module.render_visualization(None, options)  # type: ignore[arg-type]
