from __future__ import annotations

import tempfile
import time
from pathlib import Path

from app.utils.call_timeline import _TimelineWriter


def test_queue_full_is_counted_and_flush_honors_timeout() -> None:
    writer = _TimelineWriter(max_queue=1, warning_interval_s=3_600)
    writer.start = lambda: True  # type: ignore[method-assign]
    writer._last_drop_warning_at = time.monotonic()

    assert writer.submit(Path("unused"), "first") is True
    assert writer.submit(Path("unused"), "second") is False

    started = time.monotonic()
    assert writer.flush(timeout=0.01) is False
    assert time.monotonic() - started < 0.5
    assert writer.dropped == 1


def test_write_error_is_counted_without_killing_writer() -> None:
    writer = _TimelineWriter(max_queue=10, warning_interval_s=3_600)
    writer._last_error_warning_at = time.monotonic()
    with tempfile.TemporaryDirectory() as tmpdir:
        invalid_path = Path(tmpdir)
        assert writer.submit(invalid_path, "line") is True
        assert writer.flush(timeout=2.0) is True

    assert writer.write_errors == 1
    assert writer.shutdown(timeout=2.0) is True


def test_shutdown_drains_pending_lines_and_rejects_new_work() -> None:
    writer = _TimelineWriter(max_queue=10)
    writer._last_drop_warning_at = time.monotonic()
    with tempfile.TemporaryDirectory() as tmpdir:
        path = Path(tmpdir) / "timeline.jsonl"
        assert writer.submit(path, "one") is True
        assert writer.submit(path, "two") is True
        assert writer.shutdown(timeout=2.0) is True
        assert path.read_text(encoding="utf-8").splitlines() == ["one", "two"]
        assert writer.submit(path, "three") is False

    assert writer.dropped == 1
