"""Tests for milco show detail output (human-readable and --json)."""

import json
from milco.cli import main


def _setup_run(tmp_path, monkeypatch, run_id="show-detail"):
    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", run_id])
    return tmp_path


def test_show_prints_run_id(tmp_path, monkeypatch, capsys):
    _setup_run(tmp_path, monkeypatch, "det-id")
    capsys.readouterr()

    exit_code = main(["show", "det-id"])
    assert exit_code == 0
    out = capsys.readouterr().out
    assert "det-id" in out


def test_show_prints_decision(tmp_path, monkeypatch, capsys):
    _setup_run(tmp_path, monkeypatch, "det-dec")
    capsys.readouterr()

    main(["show", "det-dec"])
    out = capsys.readouterr().out
    assert "PASS" in out


def test_show_prints_mode(tmp_path, monkeypatch, capsys):
    _setup_run(tmp_path, monkeypatch, "det-mode")
    capsys.readouterr()

    main(["show", "det-mode"])
    out = capsys.readouterr().out
    assert "dry_run" in out


def test_show_prints_artifacts_section(tmp_path, monkeypatch, capsys):
    _setup_run(tmp_path, monkeypatch, "det-art")
    capsys.readouterr()

    main(["show", "det-art"])
    out = capsys.readouterr().out
    assert "Artifacts:" in out
    assert "summary.md" in out
    assert "manifest.json" in out
    assert "sha256:" in out
    assert "bytes" in out


def test_show_prints_timestamps(tmp_path, monkeypatch, capsys):
    _setup_run(tmp_path, monkeypatch, "det-ts")
    capsys.readouterr()

    main(["show", "det-ts"])
    out = capsys.readouterr().out
    assert "Started:" in out
    assert "Finished:" in out


def test_show_json_output(tmp_path, monkeypatch, capsys):
    _setup_run(tmp_path, monkeypatch, "det-json")
    capsys.readouterr()

    exit_code = main(["show", "det-json", "--json"])
    assert exit_code == 0
    out = capsys.readouterr().out
    data = json.loads(out)
    assert data["run_id"] == "det-json"
    assert data["schema_version"] == "1.0"
    assert "outcome" in data
    assert "artifacts" in data


def test_show_json_matches_manifest_file(tmp_path, monkeypatch, capsys):
    _setup_run(tmp_path, monkeypatch, "det-match")
    capsys.readouterr()

    main(["show", "det-match", "--json"])
    out = capsys.readouterr().out
    from_show = json.loads(out)

    from_file = json.loads(
        (tmp_path / "runs" / "det-match" / "manifest.json").read_text(encoding="utf-8")
    )
    assert from_show["run_id"] == from_file["run_id"]
    assert from_show["outcome"] == from_file["outcome"]
    assert from_show["mode"] == from_file["mode"]
