"""Tests for AuditRecorder."""

import json

import pytest

from fliiq.runtime.planning.audit import AuditRecorder
from fliiq.runtime.planning.models import Plan, PlanStep


def _make_plan() -> Plan:
    return Plan(
        prompt="test prompt",
        goal="test goal",
        steps=[
            PlanStep(title="step 1", description="do thing"),
            PlanStep(title="step 2", description="do other thing"),
        ],
    )


def test_audit_save(tmp_path):
    audit_dir = tmp_path / "audit"
    recorder = AuditRecorder(prompt="test prompt", audit_dir=audit_dir)
    recorder.record_plan(_make_plan())
    recorder.record_event("custom_event", {"key": "value"})
    path = recorder.save()

    assert path.exists()
    assert path.suffix == ".json"

    data = json.loads(path.read_text())
    assert data["prompt"] == "test prompt"
    assert data["plan"]["goal"] == "test goal"
    assert len(data["plan"]["steps"]) == 2
    assert data["completed_at"] is not None

    # Verify events
    events = [e["event"] for e in data["entries"]]
    assert "session_started" in events
    assert "plan_generated" in events
    assert "custom_event" in events
    assert "session_completed" in events


def test_audit_creates_directory(tmp_path):
    audit_dir = tmp_path / "deep" / "nested" / "audit"
    recorder = AuditRecorder(prompt="test", audit_dir=audit_dir)
    path = recorder.save()

    assert audit_dir.exists()
    assert path.exists()


def test_audit_without_plan(tmp_path):
    audit_dir = tmp_path / "audit"
    recorder = AuditRecorder(prompt="no plan", audit_dir=audit_dir)
    path = recorder.save()

    data = json.loads(path.read_text())
    assert data["plan"] is None
