"""Tests for deterministic gate exit codes (PASS/FAIL)."""

from milco.core.run_context import RunContext
from milco.core.artifacts import write_artifact, all_artifacts_present
from milco.gate.gates import run_gates


def _make_ctx(tmp_path, apply=False, confirm=False):
    contract = tmp_path / "TASK_CONTRACT.md"
    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\n"
    )
    if confirm:
        text += "CONFIRM APPLY\n\n"
    else:
        text += "None.\n\n"
    text += "## Notes\n\nNone.\n"
    contract.write_text(text, encoding="utf-8")
    return RunContext(
        repo_root=tmp_path,
        run_id="test-exit",
        apply_mode=apply,
        contract_path=str(contract),
    )


def test_gate_pass_dry_run(tmp_path):
    """A well-formed dry-run should yield exit_code 0 and overall_status PASS."""
    ctx = _make_ctx(tmp_path)
    ctx.ensure_run_dir()
    write_artifact(ctx, "evidence.md", "# Evidence\n\nFile data here.\n")
    write_artifact(ctx, "patches.diff", "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n")
    write_artifact(
        ctx,
        "summary.md",
        "# Summary\n\n## Plan\n\n### Step 1: Scan\n\n- tool: scan\n",
    )

    report = run_gates(ctx)

    assert report["exit_code"] == 0
    assert report["overall_status"] == "PASS"


def test_gate_fail_missing_evidence(tmp_path):
    """Run gate without evidence.md -> policy evidence_first fails -> FAIL."""
    ctx = _make_ctx(tmp_path)
    ctx.ensure_run_dir()
    # Deliberately leave evidence.md empty
    write_artifact(ctx, "evidence.md", "")
    write_artifact(ctx, "patches.diff", "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n")
    write_artifact(ctx, "summary.md", "")

    report = run_gates(ctx)

    assert report["exit_code"] == 1
    assert report["overall_status"] == "FAIL"
    policy_gate = next(g for g in report["gates"] if g["name"] == "policy")
    assert policy_gate["status"] == "FAIL"


def test_gate_artifacts_exist_on_fail(tmp_path):
    """Even on FAIL, all 5 artifacts must be present."""
    ctx = _make_ctx(tmp_path)
    ctx.ensure_run_dir()
    write_artifact(ctx, "evidence.md", "")
    write_artifact(ctx, "patches.diff", "")
    write_artifact(ctx, "summary.md", "")

    run_gates(ctx)

    assert all_artifacts_present(ctx)
