"""History v0 — read-only index.jsonl reader and formatter."""

from __future__ import annotations

import json
import pathlib
import sys
from typing import Any

from milco.core.run_index import INDEX_FILENAME

MAX_CORRUPT_WARNINGS = 3


def load_index_records(runs_dir: pathlib.Path) -> tuple[list[dict[str, Any]], int]:
    """Load all records from index.jsonl. Returns (records, corrupt_count)."""
    index_path = runs_dir / INDEX_FILENAME
    if not index_path.exists():
        return [], -1  # -1 signals file missing
    text = index_path.read_text(encoding="utf-8")
    if not text.strip():
        return [], -2  # -2 signals file empty

    records: list[dict[str, Any]] = []
    corrupt = 0
    for i, line in enumerate(text.splitlines(), 1):
        line = line.strip()
        if not line:
            continue
        try:
            records.append(json.loads(line))
        except json.JSONDecodeError:
            corrupt += 1
            if corrupt <= MAX_CORRUPT_WARNINGS:
                print(f"Warning: corrupt index line {i}: {line[:80]}", file=sys.stderr)
    return records, corrupt


def filter_records(
    records: list[dict[str, Any]],
    last: int | None = None,
    failed_only: bool = False,
) -> list[dict[str, Any]]:
    """Filter and slice records."""
    result = records
    if failed_only:
        result = [r for r in result if r.get("exit_code") == 1]
    if last is not None and last > 0:
        result = result[-last:]
    return result


def format_table(records: list[dict[str, Any]]) -> str:
    """Format records as a fixed-width text table."""
    if not records:
        return "No matching runs."

    headers = ["timestamp", "run_id", "decision", "exit_code", "mode", "command"]

    col_widths = {h: len(h) for h in headers}
    rows: list[dict[str, str]] = []
    for r in records:
        row = {
            "timestamp": str(r.get("timestamp", "")),
            "run_id": str(r.get("run_id", "")),
            "decision": str(r.get("decision", "")),
            "exit_code": str(r.get("exit_code", "")),
            "mode": str(r.get("mode", "")),
            "command": str(r.get("command", "")),
        }
        for h in headers:
            col_widths[h] = max(col_widths[h], len(row[h]))
        rows.append(row)

    def _fmt_row(vals: dict[str, str]) -> str:
        parts = [vals[h].ljust(col_widths[h]) for h in headers]
        return "  ".join(parts)

    header_row = _fmt_row({h: h for h in headers})
    sep = "  ".join("-" * col_widths[h] for h in headers)
    lines = [header_row, sep]
    for row in rows:
        lines.append(_fmt_row(row))
    return "\n".join(lines)


def format_json(records: list[dict[str, Any]]) -> str:
    """Format records as JSON lines."""
    if not records:
        return ""
    return "\n".join(json.dumps(r) for r in records)
