"""Tests for milco show when run is missing or no runs exist."""

from milco.cli import main


def test_show_no_runs_exits_0(tmp_path, monkeypatch, capsys):
    """No runs dir at all -> lists nothing, exit 0."""
    monkeypatch.chdir(tmp_path)
    exit_code = main(["show"])
    assert exit_code == 0
    out = capsys.readouterr().out
    assert "No runs found" in out


def test_show_lists_available_runs(tmp_path, monkeypatch, capsys):
    """When runs exist but no run_id given, list them."""
    contract = tmp_path / "TASK_CONTRACT.md"
    contract.write_text(
        "# Task Contract\n\n"
        "## Goal\n\nTest.\n\n## Scope\n\nTest.\n\n"
        "## Out of scope\n\nNone.\n\n## Success Criteria\n\nPass.\n\n"
        "## Constraints\n\nNone.\n\n## Approvals required\n\nNone.\n\n"
        "## Notes\n\nNone.\n",
        encoding="utf-8",
    )
    monkeypatch.chdir(tmp_path)
    main(["run", "--contract", str(contract), "--run-id", "list-me"])

    capsys.readouterr()  # clear run output
    exit_code = main(["show"])
    assert exit_code == 0
    out = capsys.readouterr().out
    assert "list-me" in out
    assert "Available" in out


def test_show_nonexistent_run_exits_1(tmp_path, monkeypatch, capsys):
    monkeypatch.chdir(tmp_path)
    exit_code = main(["show", "does-not-exist"])
    assert exit_code == 1
    err = capsys.readouterr().err
    assert "not found" in err.lower()


def test_show_missing_manifest_exits_1(tmp_path, monkeypatch, capsys):
    """Run dir exists but manifest.json is missing."""
    run_dir = tmp_path / "runs" / "no-manifest"
    run_dir.mkdir(parents=True)
    monkeypatch.chdir(tmp_path)
    exit_code = main(["show", "no-manifest"])
    assert exit_code == 1
    err = capsys.readouterr().err
    assert "manifest.json missing" in err
