"""Unit tests for the lenses: honest-absence, derived ages, the aggregate."""

from __future__ import annotations

from pathlib import Path

from mgf.fedres import DiskProvider, ReadResult, SyncState

from mgf.fed_web.lenses import (
    ProjectMeta,
    _absence,
    _age,
    architecture_lens,
    assemble_meta,
    decisions_lens,
    federation_state,
    inprogress_lens,
    roadmap_lens,
    unknown_meta,
)

from .conftest import requires_real_federation


def _meta(slug: str, state: str) -> ProjectMeta:
    return ProjectMeta(
        slug=slug,
        name=slug,
        kind="lib",
        wired=state not in ("UNKNOWN", "UNREADABLE"),
        sync_state=state,
        sync_detail="",
        sync_reason=None,
        source_commit=None,
        head_commit=None,
        generated_at=None,
    )


def test_age_is_honest_about_absence() -> None:
    assert _age(None) is None
    assert _age("not-a-date") is None
    assert _age("2020-01-01T00:00:00Z") is not None  # a derived, non-empty string


def test_absence_unknown_reads_nothing_reported() -> None:
    res = ReadResult(False, None, None, SyncState.UNKNOWN, "not found")
    out = _absence("roadmap", res)
    assert out["ok"] is False
    assert out["state"] == "UNKNOWN"
    assert out["title"] == "Nothing reported yet"


def test_absence_unreadable_surfaces_reason_and_errors() -> None:
    res = ReadResult(False, "roadmap", None, SyncState.UNREADABLE, "bad", ("stages: nope",))
    out = _absence("roadmap", res)
    assert out["state"] == "UNREADABLE"
    assert out["errors"] == ["stages: nope"]
    assert out["action"]


def test_lenses_render_honest_absence_on_bare_provider(tmp_path: Path) -> None:
    provider = DiskProvider(tmp_path)  # no fed-resources/ at all
    for lens in (roadmap_lens, architecture_lens, inprogress_lens, decisions_lens):
        view = lens(provider)
        assert view["ok"] is False
        assert view["state"] == "UNKNOWN"


@requires_real_federation
def test_lenses_compose_real_fedres_status_and_roadmap() -> None:
    from .conftest import WORKSPACE

    provider = DiskProvider(WORKSPACE / "mgf-fedres")
    rm = roadmap_lens(provider)
    assert rm["ok"] and len(rm["stages"]) >= 1
    ip = inprogress_lens(provider)
    assert ip["ok"] and "items" in ip


@requires_real_federation
def test_architecture_graph_groups_by_layer_real_standard() -> None:
    from .conftest import WORKSPACE

    view = architecture_lens(DiskProvider(WORKSPACE / "mgf-standard"))
    assert view["ok"] and view["mode"] == "graph"
    assert view["counts"]["nodes"] >= 30
    # every node is placed under some layer group (none silently dropped)
    placed = sum(len(g["nodes"]) for g in view["grouped"])
    assert placed == view["counts"]["nodes"]


def test_federation_aggregate_picks_worst_actionable() -> None:
    fed = federation_state([_meta("a", "IN_SYNC"), _meta("b", "STALE")])
    assert fed["state"] == "STALE"
    assert fed["all_synced"] is False
    assert "1 stale" in fed["counts"]


def test_federation_all_in_sync() -> None:
    fed = federation_state([_meta("a", "IN_SYNC"), _meta("b", "IN_SYNC")])
    assert fed["all_synced"] is True
    assert fed["label"] == "All in sync"


def test_federation_empty_is_safe() -> None:
    fed = federation_state([])
    assert fed["state"] == "IN_SYNC"
    assert fed["all_synced"] is False


def test_assemble_meta_on_bare_provider_is_unknown(tmp_path: Path) -> None:
    meta = assemble_meta("ghost", DiskProvider(tmp_path))
    assert meta.sync_state == "UNKNOWN"
    assert meta.wired is False


def test_unknown_meta_is_unwired() -> None:
    meta = unknown_meta("ghost")
    assert meta.sync_state == "UNKNOWN"
    assert meta.wired is False
    assert meta.source_short == "—"
