"""Artifact writers – ensure the 5 required run artifacts exist."""

from __future__ import annotations

import json
import pathlib
from typing import Any

from milco.core.run_context import RunContext

REQUIRED_ARTIFACTS = [
    "task_contract.md",
    "evidence.md",
    "patches.diff",
    "gate_report.json",
    "summary.md",
]


def write_artifact(ctx: RunContext, name: str, content: str) -> pathlib.Path:
    ctx.ensure_run_dir()
    path = ctx.artifact_path(name)
    path.write_text(content, encoding="utf-8")
    return path


def write_json_artifact(ctx: RunContext, name: str, data: Any) -> pathlib.Path:
    return write_artifact(ctx, name, json.dumps(data, indent=2) + "\n")


def ensure_all_artifacts_exist(ctx: RunContext) -> None:
    """Create any missing artifacts with placeholder content."""
    ctx.ensure_run_dir()
    for name in REQUIRED_ARTIFACTS:
        path = ctx.artifact_path(name)
        if not path.exists():
            if name.endswith(".json"):
                path.write_text("{}\n", encoding="utf-8")
            else:
                path.write_text(f"# {name}\n\n_Not yet generated._\n", encoding="utf-8")


def all_artifacts_present(ctx: RunContext) -> bool:
    return all(ctx.artifact_path(n).exists() for n in REQUIRED_ARTIFACTS)
