from __future__ import annotations

import json
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock

from blackbox.dashboard.routes import build_session_info, mark_live
from blackbox.models import SessionInfo

# ---------------------------------------------------------------------------
# mark_live
# ---------------------------------------------------------------------------


class TestMarkLive:
    def make_session(self, session_id: str = "sess-1") -> SessionInfo:
        return SessionInfo(
            session_id=session_id,
            project_path="proj",
            project_name="proj",
            transcript_path="/tmp/proj/sess.jsonl",
            started_at=1_000_000.0,
        )

    def test_no_live_ids_returns_same_list(self) -> None:
        watcher = MagicMock()
        watcher.live_session_ids.return_value = set()
        sessions = [self.make_session()]
        result = mark_live(sessions, watcher)
        assert result is sessions

    def test_marks_matching_session_as_live(self) -> None:
        watcher = MagicMock()
        watcher.live_session_ids.return_value = {"sess-1"}
        sessions = [self.make_session("sess-1"), self.make_session("sess-2")]
        result = mark_live(sessions, watcher)
        assert result[0].is_live is True
        assert result[1].is_live is False

    def test_non_matching_sessions_unchanged(self) -> None:
        watcher = MagicMock()
        watcher.live_session_ids.return_value = {"other"}
        sessions = [self.make_session("sess-1")]
        result = mark_live(sessions, watcher)
        assert result[0].is_live is False


# ---------------------------------------------------------------------------
# build_session_info
# ---------------------------------------------------------------------------


class TestBuildSessionInfo:
    def write_transcript(self, path: Path, entries: list[dict[str, Any]]) -> None:
        path.write_text("\n".join(json.dumps(e) for e in entries))

    def test_returns_info_from_transcript(self, tmp_path: Path) -> None:
        path = tmp_path / "abc.jsonl"
        self.write_transcript(
            path,
            [{"type": "user", "timestamp": "2024-01-01T00:00:00Z", "message": {"content": "hello"}}],
        )
        info = build_session_info(path, "abc", "proj")
        assert "abc" == info.session_id
        assert "hello" == info.first_prompt

    def test_fallback_for_empty_transcript(self, tmp_path: Path) -> None:
        path = tmp_path / "empty.jsonl"
        path.write_text("")
        info = build_session_info(path, "empty", "proj")
        assert "empty" == info.session_id
        assert "proj" == info.project_name
        assert "" == info.first_prompt
