"""CLI + live-channel tests — exercise main() (covers cli.py, live.py end-to-end)."""

from __future__ import annotations

import json
from importlib.resources import files
from pathlib import Path

import pytest

from mgf.fedres.cli import main
from mgf.fedres.validate import main as validate_main

PROJECT = '[project]\nid = "demo"\nname = "Demo"\nkind = "library"\n'
STATUS = '[[tasks]]\nid = "T-1"\ntitle = "demo task"\nstate = "in_progress"\n'


def _proj(root: Path) -> Path:
    src = root / "fed-resources" / "source"
    src.mkdir(parents=True)
    (src / "project.toml").write_text(PROJECT, encoding="utf-8")
    (src / "status.toml").write_text(STATUS, encoding="utf-8")
    return root


def test_generate_then_check_in_sync(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    _proj(tmp_path)
    assert main(["-C", str(tmp_path), "generate"]) == 0
    assert main(["-C", str(tmp_path), "check"]) == 0
    assert "IN_SYNC" in capsys.readouterr().out


def test_check_gate_nonzero_when_unknown(tmp_path: Path) -> None:
    assert main(["-C", str(tmp_path), "check"]) == 1  # no fed-resources -> UNKNOWN -> gate fails


def test_check_stale_after_source_edit(tmp_path: Path) -> None:
    root = _proj(tmp_path)
    main(["-C", str(root), "generate"])
    (root / "fed-resources" / "source" / "status.toml").write_text(
        STATUS + '[[tasks]]\nid = "T-2"\ntitle = "x"\nstate = "todo"\n', encoding="utf-8"
    )
    assert main(["-C", str(root), "check"]) == 1  # STALE


def test_status_command(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    _proj(tmp_path)
    main(["-C", str(tmp_path), "generate"])
    assert main(["-C", str(tmp_path), "status"]) == 0
    assert "IN_SYNC" in capsys.readouterr().out


def test_generate_json_output(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    _proj(tmp_path)
    assert main(["-C", str(tmp_path), "--format", "json", "generate"]) == 0
    payload = json.loads(capsys.readouterr().out)
    assert payload["regenerated"] is True
    assert "status.json" in payload["files"]


def test_run_ok_and_check_stays_in_sync(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    root = _proj(tmp_path)
    main(["-C", str(root), "generate"])
    rc = main(
        ["-C", str(root), "run", "demo", "--task", "T-1", "--", "python3", "-c", "print('hi')"]
    )
    assert rc == 0
    assert "ok" in capsys.readouterr().out
    # the run-record folded into the manifest -> gate still green
    assert main(["-C", str(root), "check"]) == 0


def test_run_failure_exits_nonzero(tmp_path: Path) -> None:
    root = _proj(tmp_path)
    main(["-C", str(root), "generate"])
    rc = main(["-C", str(root), "run", "boom", "--", "python3", "-c", "import sys; sys.exit(3)"])
    assert rc == 1


def test_run_without_command_errors(tmp_path: Path) -> None:
    root = _proj(tmp_path)
    main(["-C", str(root), "generate"])
    assert main(["-C", str(root), "run", "noop"]) == 2


def test_tail_no_session(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    _proj(tmp_path)
    main(["-C", str(tmp_path), "generate"])
    assert main(["-C", str(tmp_path), "tail"]) == 0
    assert "no live session" in capsys.readouterr().out


def test_validate_cli(tmp_path: Path) -> None:
    example = str(Path(str(files("mgf.fedres"))) / "examples" / "status.json")
    assert validate_main([example]) == 0
    bad = tmp_path / "bad.json"
    bad.write_text('{"schema_version": "0.1", "kind": "status"}', encoding="utf-8")
    assert validate_main([str(bad)]) == 1
    assert validate_main([]) == 2
