"""Tests that runs/index.jsonl is created and appended on milco run."""

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

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

    assert (tmp_path / "runs" / "index.jsonl").exists()


def test_index_has_one_line(tmp_path, monkeypatch):
    contract = _write_contract(tmp_path)
    monkeypatch.chdir(tmp_path)

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

    lines = (
        (tmp_path / "runs" / "index.jsonl")
        .read_text(encoding="utf-8")
        .strip()
        .splitlines()
    )
    assert len(lines) >= 1


def test_index_record_required_keys(tmp_path, monkeypatch):
    contract = _write_contract(tmp_path)
    monkeypatch.chdir(tmp_path)

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

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

    required = [
        "schema_version",
        "timestamp",
        "run_id",
        "command",
        "mode",
        "decision",
        "exit_code",
        "git",
        "paths",
    ]
    for key in required:
        assert key in record, f"Missing index key: {key}"

    assert "commit" in record["git"]
    assert "branch" in record["git"]
    assert "run_dir" in record["paths"]
    assert "manifest" in record["paths"]


def test_index_run_id_matches(tmp_path, monkeypatch):
    contract = _write_contract(tmp_path)
    monkeypatch.chdir(tmp_path)

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

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


def test_index_appends_multiple_runs(tmp_path, monkeypatch):
    contract = _write_contract(tmp_path)
    monkeypatch.chdir(tmp_path)

    main(["run", "--contract", str(contract), "--run-id", "idx-a"])
    main(["run", "--contract", str(contract), "--run-id", "idx-b"])

    lines = (
        (tmp_path / "runs" / "index.jsonl")
        .read_text(encoding="utf-8")
        .strip()
        .splitlines()
    )
    assert len(lines) == 2
    assert json.loads(lines[0])["run_id"] == "idx-a"
    assert json.loads(lines[1])["run_id"] == "idx-b"
