"""Smoke + unit tests for the mgf-fed status tracker."""

from __future__ import annotations

import json
from pathlib import Path

from mgf.fed._roster import members
from mgf.fed._status import RepoStatus, render_table, scan


def _fake_root(tmp_path: Path) -> Path:
    """Build a minimal federation root with a registry + two member repos."""
    reg = {
        "release_waves": [["mgf-common"], ["mgf-foo"]],
        "libraries": [
            {
                "repo": "mgf-common",
                "lang": "python",
                "version": "0.46.7",
                "extras": ["dev", "standards"],
                "deps": {},
                "used_by": ["mgf-foo"],
            },
            {
                "repo": "mgf-foo",
                "lang": "python",
                "version": "0.1.0",
                "extras": ["dev"],
                "deps": {"mgf-common": ">=0.46"},
                "used_by": [],
            },
        ],
    }
    (tmp_path / "mgf-standard").mkdir()
    (tmp_path / "mgf-standard" / "MGF_LIBRARIES.json").write_text(json.dumps(reg), encoding="utf-8")
    # mgf-foo: a conformant-looking repo with a small ledger
    foo = tmp_path / "mgf-foo"
    (foo / "docs" / "inprogress").mkdir(parents=True)
    (foo).joinpath("pyproject.toml").write_text('[project]\nname = "mgf-foo"\nversion = "0.1.0"\n')
    (foo / ".woodpecker.yml").write_text("steps: []\n")
    (foo / "PUBLIC_API.json").write_text("{}\n")
    (foo / "docs" / "inprogress" / "MGF_STANDARDS_CONFORMANCE.md").write_text(
        "| DP-01 | ✅ | x | y |\n| DP-02 | ⏳ | x | y |\n| EH-04 | N/A | x | y |\n"
    )
    # mgf-common: bare (no scaffolding) to exercise the missing-file paths
    (tmp_path / "mgf-common").mkdir()
    (tmp_path / "mgf-common" / "pyproject.toml").write_text(
        '[project]\nname = "mgf-common"\nversion = "0.46.7"\n'
    )
    return tmp_path


def test_members_parse_waves(tmp_path: Path) -> None:
    ms = members(_fake_root(tmp_path))
    assert [m.repo for m in ms] == ["mgf-common", "mgf-foo"]
    assert ms[0].wave == 0 and ms[1].wave == 1
    assert ms[0].has_standards_extra and not ms[1].has_standards_extra


def test_scan_conformance_and_scaffolding(tmp_path: Path) -> None:
    root = _fake_root(tmp_path)
    foo = next(m for m in members(root) if m.repo == "mgf-foo")
    st = scan(foo)
    assert st.has_ci and st.has_public_api and st.has_ledger
    assert st.conf_ok == 1 and st.conf_wip == 1 and st.conf_na == 1
    assert st.conf_pct == 50  # 1 of (1+1) applicable
    assert st.version_synced is True


def test_render_table_runs(tmp_path: Path) -> None:
    rows = [scan(m) for m in members(_fake_root(tmp_path))]
    out = render_table(rows)
    assert "repo" in out and "mgf-foo" in out and "avg conf" in out
    assert isinstance(out, str)


def test_repostatus_is_frozen() -> None:
    import dataclasses

    f = RepoStatus.__dataclass_fields__
    assert f and dataclasses.fields(RepoStatus)  # sanity: it's a dataclass
