"""Tests that manifest.json is written even on REFUSED outcome."""

import json
from milco.cli import main
from milco.core.run_context import RunContext
from milco.core.artifacts import all_artifacts_present


def _write_contract_no_confirm(tmp_path):
    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",
    )
    return contract


def test_refused_exit_code_1(tmp_path, monkeypatch):
    contract = _write_contract_no_confirm(tmp_path)
    monkeypatch.chdir(tmp_path)

    exit_code = main(
        [
            "run",
            "--apply",
            "--contract",
            str(contract),
            "--run-id",
            "mr-exit",
        ]
    )
    assert exit_code == 1


def test_refused_manifest_exists(tmp_path, monkeypatch):
    contract = _write_contract_no_confirm(tmp_path)
    monkeypatch.chdir(tmp_path)

    main(
        [
            "run",
            "--apply",
            "--contract",
            str(contract),
            "--run-id",
            "mr-exists",
        ]
    )

    manifest_path = tmp_path / "runs" / "mr-exists" / "manifest.json"
    assert manifest_path.exists()


def test_refused_manifest_outcome(tmp_path, monkeypatch):
    contract = _write_contract_no_confirm(tmp_path)
    monkeypatch.chdir(tmp_path)

    main(
        [
            "run",
            "--apply",
            "--contract",
            str(contract),
            "--run-id",
            "mr-outcome",
        ]
    )

    data = json.loads(
        (tmp_path / "runs" / "mr-outcome" / "manifest.json").read_text(encoding="utf-8")
    )
    assert data["outcome"]["decision"] == "REFUSED"
    assert data["outcome"]["exit_code"] == 1


def test_refused_summary_decision_line(tmp_path, monkeypatch):
    contract = _write_contract_no_confirm(tmp_path)
    monkeypatch.chdir(tmp_path)

    main(
        [
            "run",
            "--apply",
            "--contract",
            str(contract),
            "--run-id",
            "mr-decision",
        ]
    )

    summary = (tmp_path / "runs" / "mr-decision" / "summary.md").read_text(
        encoding="utf-8"
    )
    assert summary.startswith("DECISION: REFUSED")


def test_refused_all_artifacts_present(tmp_path, monkeypatch):
    contract = _write_contract_no_confirm(tmp_path)
    monkeypatch.chdir(tmp_path)

    main(
        [
            "run",
            "--apply",
            "--contract",
            str(contract),
            "--run-id",
            "mr-arts",
        ]
    )

    ctx = RunContext(repo_root=tmp_path, run_id="mr-arts")
    assert all_artifacts_present(ctx)
