"""Per-job run history logging."""

import json
from pathlib import Path

from fliiq.runtime.scheduler.models import RunLogEntry


def _runs_dir(job_name: str, jobs_dir: Path) -> Path:
    return jobs_dir / job_name / "runs"


def save_run_log(entry: RunLogEntry, jobs_dir: Path) -> Path:
    """Save a run log entry. Returns the file path."""
    runs = _runs_dir(entry.job_name, jobs_dir)
    runs.mkdir(parents=True, exist_ok=True)

    ts = entry.started_at.strftime("%Y%m%dT%H%M%S_%f")
    path = runs / f"{ts}.json"

    path.write_text(
        json.dumps(entry.model_dump(mode="json"), indent=2),
        encoding="utf-8",
    )
    return path


def load_run_logs(
    job_name: str, jobs_dir: Path, limit: int = 20
) -> list[RunLogEntry]:
    """Load the most recent N run logs for a job, newest first."""
    runs = _runs_dir(job_name, jobs_dir)
    if not runs.is_dir():
        return []

    files = sorted(runs.glob("*.json"), reverse=True)[:limit]
    entries: list[RunLogEntry] = []
    for f in files:
        raw = json.loads(f.read_text(encoding="utf-8"))
        entries.append(RunLogEntry(**raw))
    return entries


def get_latest_run(job_name: str, jobs_dir: Path) -> RunLogEntry | None:
    """Get the most recent run log entry, or None."""
    logs = load_run_logs(job_name, jobs_dir, limit=1)
    return logs[0] if logs else None
