"""Append-only JSONL trial log. Source of truth — ADR-0006.

The SQLite index (M2) is a derived, fully-rebuildable cache over this file;
deleting it is never data loss. Deleting a run's trials.jsonl is.
"""

from __future__ import annotations

from collections.abc import Iterator
from pathlib import Path

from ablate.record import TrialRecord


class TrialLog:
    def __init__(self, run_dir: Path):
        self.run_dir = run_dir
        self.run_dir.mkdir(parents=True, exist_ok=True)
        self.path = run_dir / "trials.jsonl"

    def append(self, record: TrialRecord) -> None:
        # One JSON object per line, flushed immediately: a crash mid-run must
        # not lose already-completed trials.
        with self.path.open("a") as f:
            f.write(record.model_dump_json() + "\n")
            f.flush()

    def read_all(self) -> list[TrialRecord]:
        return list(self.iter_records())

    def iter_records(self) -> Iterator[TrialRecord]:
        if not self.path.exists():
            return
        with self.path.open() as f:
            for line in f:
                line = line.strip()
                if line:
                    yield TrialRecord.model_validate_json(line)
