"""Tests for the event logger."""

import json
import tempfile
from datetime import datetime, timezone
from pathlib import Path

from agent_preflight.events import EventLogger


class TestEventLogger:
    def test_write_and_read(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "events.jsonl"
            with EventLogger(path) as logger:
                logger.log("tool_start", tool="bash")
                logger.log("tool_end", tool="bash", exit_code=0)

            events = EventLogger.read(path)
            assert len(events) == 2
            assert events[0]["type"] == "tool_start"
            assert events[0]["tool"] == "bash"
            assert "timestamp" in events[0]
            assert "elapsed_s" in events[0]
            assert events[1]["exit_code"] == 0

    def test_read_nonexistent_file(self):
        events = EventLogger.read(Path("/nonexistent/events.jsonl"))
        assert events == []

    def test_read_handles_corrupt_lines(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "events.jsonl"
            path.write_text('{"type":"ok"}\nnot json\n{"type":"also ok"}\n')
            events = EventLogger.read(path)
            assert len(events) == 2
            assert events[0]["type"] == "ok"
            assert events[1]["type"] == "also ok"

    def test_creates_parent_dirs(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "deep" / "nested" / "events.jsonl"
            with EventLogger(path) as logger:
                logger.log("test")
            assert path.exists()

    def test_append_mode(self):
        """Second logger appends, does not overwrite."""
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "events.jsonl"
            with EventLogger(path) as logger:
                logger.log("first")
            with EventLogger(path) as logger:
                logger.log("second")
            events = EventLogger.read(path)
            assert len(events) == 2

    def test_start_time_controls_elapsed_seconds(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "events.jsonl"
            start = datetime.now(timezone.utc)
            with EventLogger(path, start_time=start) as logger:
                logger.log("tick")

            events = EventLogger.read(path)
            assert events[0]["elapsed_s"] >= 0.0

    def test_elapsed_seconds_can_be_disabled(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "events.jsonl"
            with EventLogger(path, include_elapsed_s=False) as logger:
                logger.log("tick")

            events = EventLogger.read(path)
            assert "elapsed_s" not in events[0]
