from __future__ import annotations

import json
import time
from pathlib import Path
from typing import Any


IMPORTANT_EVENTS = {
    "ready_sent",
    "client_audio_first_frame_received",
    "client_audio_first_frame_published",
    "client_audio_activity_detected",
    "agent_join",
    "user_transcript_final",
    "stt_final",
    "stt_http_completed",
    "tts_stage_started",
    "tts_stage_result",
    "done_packet_received",
    "stop_sent",
    "bridge_failed",
    "call_end",
}

ERROR_EVENTS = {
    "bridge_failed",
    "stt_http_failed",
    "stt_http_failed_nonfatal",
    "tts_error",
    "tts_stage_failed",
    "agent_reconnect_exhausted",
}


def read_timeline(path: Path | str) -> list[dict[str, Any]]:
    timeline_path = Path(path)
    if not timeline_path.exists():
        return []
    records: list[dict[str, Any]] = []
    for line in timeline_path.read_text(encoding="utf-8").splitlines():
        if not line.strip():
            continue
        try:
            payload = json.loads(line)
        except json.JSONDecodeError:
            continue
        if isinstance(payload, dict):
            records.append(payload)
    return records


def wait_for_timeline(path: Path | str, *, timeout_s: float = 5.0) -> list[dict[str, Any]]:
    deadline = time.monotonic() + timeout_s
    timeline_path = Path(path)
    while time.monotonic() < deadline:
        records = read_timeline(timeline_path)
        if records:
            return records
        time.sleep(0.1)
    return read_timeline(timeline_path)


def excerpt_timeline(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
    return [
        record
        for record in records
        if str(record.get("event") or "") in IMPORTANT_EVENTS
    ]


def timeline_has_error(records: list[dict[str, Any]]) -> bool:
    return any(str(record.get("event") or "") in ERROR_EVENTS for record in records)
