"""Tests for agent audit trail extraction and saving."""

import json

import pytest

from fliiq.runtime.agent.audit import AgentAuditTrail, extract_audit_trail, save_audit_trail


def test_extract_text_messages():
    """Extract audit from simple text messages."""
    messages = [
        {"role": "user", "content": "What time is it?"},
        {"role": "assistant", "content": "It's 12:00 PM UTC."},
    ]

    trail = extract_audit_trail("What time is it?", messages, stop_reason="end_turn")

    assert trail.prompt == "What time is it?"
    assert trail.stop_reason == "end_turn"
    assert len(trail.entries) == 2
    assert trail.entries[0].role == "user"
    assert trail.entries[1].role == "assistant"
    assert trail.total_iterations == 1


def test_extract_with_tool_calls():
    """Extract audit from messages with tool_use content blocks."""
    messages = [
        {"role": "user", "content": "What time is it?"},
        {
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Let me check."},
                {"type": "tool_use", "id": "tc_1", "name": "get_time", "input": {"tz": "UTC"}},
            ],
        },
        {
            "role": "user",
            "content": [
                {"type": "tool_result", "tool_use_id": "tc_1", "content": "12:00 UTC"},
            ],
        },
        {"role": "assistant", "content": "It's 12:00 UTC."},
    ]

    trail = extract_audit_trail("What time is it?", messages)

    assert len(trail.entries) == 4
    assert trail.total_iterations == 2

    # Check tool call extraction
    assistant_entry = trail.entries[1]
    assert len(assistant_entry.tool_calls) == 1
    assert assistant_entry.tool_calls[0]["name"] == "get_time"

    # Check tool result extraction
    result_entry = trail.entries[2]
    assert len(result_entry.tool_results) == 1
    assert result_entry.tool_results[0]["tool_use_id"] == "tc_1"


def test_save_and_load(tmp_path):
    """Save audit trail to disk and verify JSON structure."""
    trail = AgentAuditTrail(prompt="test prompt", total_iterations=1, stop_reason="end_turn")

    path = save_audit_trail(trail, audit_dir=tmp_path)

    assert path.exists()
    data = json.loads(path.read_text())
    assert data["prompt"] == "test prompt"
    assert data["total_iterations"] == 1
    assert data["stop_reason"] == "end_turn"


def test_save_creates_directory(tmp_path):
    """save_audit_trail creates the audit directory if missing."""
    audit_dir = tmp_path / "nested" / "audit"
    trail = AgentAuditTrail(prompt="test")

    path = save_audit_trail(trail, audit_dir=audit_dir)
    assert path.exists()
    assert audit_dir.is_dir()


def test_extract_empty_messages():
    """Extract from empty messages produces empty trail."""
    trail = extract_audit_trail("test", [])
    assert trail.total_iterations == 0
    assert len(trail.entries) == 0
