"""Tests that index record fields match manifest.json values."""

import json
from milco.cli import main


def _write_contract(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 _run_and_load(tmp_path, monkeypatch, run_id):
    contract = _write_contract(tmp_path)
    monkeypatch.chdir(tmp_path)

    main(["run", "--contract", str(contract), "--run-id", run_id])

    manifest = json.loads(
        (tmp_path / "runs" / run_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)
    return manifest, record


def test_decision_matches(tmp_path, monkeypatch):
    manifest, record = _run_and_load(tmp_path, monkeypatch, "im-dec")
    assert record["decision"] == manifest["outcome"]["decision"]


def test_exit_code_matches(tmp_path, monkeypatch):
    manifest, record = _run_and_load(tmp_path, monkeypatch, "im-exit")
    assert record["exit_code"] == manifest["outcome"]["exit_code"]


def test_mode_matches(tmp_path, monkeypatch):
    manifest, record = _run_and_load(tmp_path, monkeypatch, "im-mode")
    assert record["mode"] == manifest["mode"]


def test_command_matches(tmp_path, monkeypatch):
    manifest, record = _run_and_load(tmp_path, monkeypatch, "im-cmd")
    assert record["command"] == manifest["command"]


def test_git_commit_matches(tmp_path, monkeypatch):
    manifest, record = _run_and_load(tmp_path, monkeypatch, "im-git")
    assert record["git"]["commit"] == manifest["repo"].get("commit")
    assert record["git"]["branch"] == manifest["repo"].get("branch")
