"""Tests for console reporting helpers."""

from __future__ import annotations

import pytest

from azure_discovery.adt_types import (
    AzureDiscoveryResponse,
    DiscoveryMergeMetrics,
    DiscoveryMetrics,
    DiscoveryPhaseMetrics,
    ResourceNode,
)
from azure_discovery.reporting.console import emit_console_summary


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


class _LoggerSpy:
    def __init__(self) -> None:
        self.records: list[tuple[str, str, dict]] = []

    def warning(self, message: str, **kwargs: dict) -> None:
        self.records.append(("warning", message, kwargs))

    def info(self, message: str, **kwargs: dict) -> None:
        self.records.append(("info", message, kwargs))


def test_emit_console_summary_warns_when_response_missing(monkeypatch: pytest.MonkeyPatch) -> None:
    spy = _LoggerSpy()
    monkeypatch.setattr("azure_discovery.reporting.console.LOGGER", spy)

    emit_console_summary(None)

    assert spy.records == [("warning", "Discovery response missing", {})]


def test_emit_console_summary_includes_core_metrics(monkeypatch: pytest.MonkeyPatch) -> None:
    response = _build_response()
    spy = _LoggerSpy()
    monkeypatch.setattr("azure_discovery.reporting.console.LOGGER", spy)

    emit_console_summary(response)

    assert len(spy.records) == 1
    level, message, kwargs = spy.records[0]
    assert level == "info"
    assert message == "Discovery summary"
    assert kwargs["extra"]["context"]["tenant_id"] == "tenant-1"


def test_emit_console_summary_includes_metrics_when_present(monkeypatch: pytest.MonkeyPatch) -> None:
    response = _build_response().model_copy(
        update={
            "metrics": DiscoveryMetrics(
                phases=[
                    DiscoveryPhaseMetrics(
                        name="azure.arm",
                        elapsed_seconds=1.23,
                        nodes_added=1,
                        relationships_added=0,
                    )
                ],
                merge=DiscoveryMergeMetrics(
                    dropped_dangling_relationships=0,
                    deduped_relationships=0,
                ),
            )
        }
    )

    spy = _LoggerSpy()
    monkeypatch.setattr("azure_discovery.reporting.console.LOGGER", spy)

    emit_console_summary(response)

    _, _, kwargs = spy.records[0]
    assert "merge_metrics" in kwargs["extra"]["context"]
    assert "phases" in kwargs["extra"]["context"]
