"""Run Index v0 — append-only JSONL index derived from manifest."""

from __future__ import annotations

import json
import pathlib
from typing import Any

INDEX_FILENAME = "index.jsonl"
INDEX_SCHEMA_VERSION = "1.0"


def build_index_record(
    manifest: dict[str, Any], run_dir: pathlib.Path
) -> dict[str, Any]:
    """Build a single index record from a finalized manifest dict."""
    return {
        "schema_version": INDEX_SCHEMA_VERSION,
        "timestamp": manifest["timestamps"]["finished_at"],
        "run_id": manifest["run_id"],
        "command": manifest["command"],
        "mode": manifest["mode"],
        "decision": manifest["outcome"]["decision"],
        "exit_code": manifest["outcome"]["exit_code"],
        "git": {
            "commit": manifest["repo"].get("commit"),
            "branch": manifest["repo"].get("branch"),
        },
        "paths": {
            "run_dir": f"runs/{manifest['run_id']}",
            "manifest": f"runs/{manifest['run_id']}/manifest.json",
        },
    }


def append_index_record(runs_dir: pathlib.Path, record: dict[str, Any]) -> pathlib.Path:
    """Append one JSON line to runs/index.jsonl."""
    runs_dir.mkdir(parents=True, exist_ok=True)
    index_path = runs_dir / INDEX_FILENAME
    line = json.dumps(record, separators=(",", ":")) + "\n"
    with index_path.open("a", encoding="utf-8") as f:
        f.write(line)
    return index_path
