"""Tests that index.jsonl records REFUSED outcome correctly."""

import json
from milco.cli import main


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(tmp_path, monkeypatch):
    contract = _write_contract_no_confirm(tmp_path)
    monkeypatch.chdir(tmp_path)

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


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

    main(
        [
            "run",
            "--apply",
            "--contract",
            str(contract),
            "--run-id",
            "ri-ref-dec",
        ]
    )

    last_line = (
        (tmp_path / "runs" / "index.jsonl")
        .read_text(encoding="utf-8")
        .strip()
        .splitlines()[-1]
    )
    record = json.loads(last_line)
    assert record["decision"] == "REFUSED"
    assert record["exit_code"] == 1


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

    main(
        [
            "run",
            "--apply",
            "--contract",
            str(contract),
            "--run-id",
            "ri-ref-id",
        ]
    )

    manifest = json.loads(
        (tmp_path / "runs" / "ri-ref-id" / "manifest.json").read_text(encoding="utf-8")
    )
    last_line = (
        (tmp_path / "runs" / "index.jsonl")
        .read_text(encoding="utf-8")
        .strip()
        .splitlines()[-1]
    )
    record = json.loads(last_line)
    assert record["run_id"] == manifest["run_id"]
