"""Tests for artifact writing and the 5-artifact invariant."""

import json
from milco.core.run_context import RunContext
from milco.core.artifacts import (
    write_artifact,
    write_json_artifact,
    ensure_all_artifacts_exist,
    all_artifacts_present,
    REQUIRED_ARTIFACTS,
)


def _make_ctx(tmp_path):
    return RunContext(repo_root=tmp_path, run_id="test-run", apply_mode=False)


def test_write_artifact(tmp_path):
    ctx = _make_ctx(tmp_path)
    path = write_artifact(ctx, "summary.md", "# Hello\n")
    assert path.exists()
    assert path.read_text(encoding="utf-8") == "# Hello\n"


def test_write_json_artifact(tmp_path):
    ctx = _make_ctx(tmp_path)
    path = write_json_artifact(ctx, "gate_report.json", {"pass": True})
    data = json.loads(path.read_text(encoding="utf-8"))
    assert data["pass"] is True


def test_ensure_all_artifacts(tmp_path):
    ctx = _make_ctx(tmp_path)
    ensure_all_artifacts_exist(ctx)
    assert all_artifacts_present(ctx)
    for name in REQUIRED_ARTIFACTS:
        assert ctx.artifact_path(name).exists()


def test_artifacts_after_audit(tmp_path):
    ctx = _make_ctx(tmp_path)
    # Write a minimal contract for audit
    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",
    )
    ctx.contract_path = str(contract)
    from milco.audit.auditor import run_audit

    run_audit(ctx)
    assert all_artifacts_present(ctx)
