"""Tests for per-job run history logging."""

import time
from datetime import datetime, timezone

from fliiq.runtime.scheduler.models import RunLogEntry
from fliiq.runtime.scheduler.run_log import (
    get_latest_run,
    load_run_logs,
    save_run_log,
)


def _make_entry(job_name: str = "test-job", status: str = "success", **kw) -> RunLogEntry:
    now = datetime.now(timezone.utc)
    return RunLogEntry(
        job_name=job_name,
        started_at=now,
        completed_at=now,
        status=status,
        duration_ms=100,
        iterations=3,
        stop_reason="end_turn",
        **kw,
    )


def test_save_and_load_run_log(tmp_path):
    entry = _make_entry()
    path = save_run_log(entry, tmp_path)
    assert path.exists()

    logs = load_run_logs("test-job", tmp_path)
    assert len(logs) == 1
    assert logs[0].status == "success"
    assert logs[0].duration_ms == 100


def test_load_ordered_with_limit(tmp_path):
    for i in range(3):
        entry = _make_entry()
        save_run_log(entry, tmp_path)
        time.sleep(0.01)  # Ensure different timestamps

    logs = load_run_logs("test-job", tmp_path, limit=2)
    assert len(logs) == 2
    # Newest first
    assert logs[0].started_at >= logs[1].started_at


def test_get_latest_run_none(tmp_path):
    result = get_latest_run("nonexistent", tmp_path)
    assert result is None


def test_get_latest_run(tmp_path):
    save_run_log(_make_entry(status="error"), tmp_path)
    time.sleep(0.01)
    save_run_log(_make_entry(status="success"), tmp_path)

    latest = get_latest_run("test-job", tmp_path)
    assert latest is not None
    assert latest.status == "success"
