import json
from pathlib import Path

import pytest

from autodebug_replay.transcripts import ReplayDivergence, load_transcripts


def _write_transcripts(tmp_path: Path, records):
    path = tmp_path / "deps_http.jsonl"
    with path.open("w", encoding="utf-8") as handle:
        for rec in records:
            handle.write(json.dumps(rec) + "\n")


def test_replay_type_specific_ordering(tmp_path):
    """Test that each type has its own position counter.

    This allows framework differences (e.g., pytest version making different
    timing calls) without affecting order of critical dependencies (HTTP, SQL).
    """
    records = [
        {"seq": 1, "type": "HTTP", "url": "http://example.com/1"},
        {"seq": 2, "type": "TIME", "ts": 1000},
        {"seq": 3, "type": "HTTP", "url": "http://example.com/2"},
        {"seq": 4, "type": "TIME", "ts": 2000},
    ]
    _write_transcripts(tmp_path, records)
    index = load_transcripts(tmp_path)

    # Can access TIME first even though HTTP has seq=1
    time1 = index.expect("TIME")
    assert time1["ts"] == 1000

    # Then access HTTP records in their order
    http1 = index.expect("HTTP")
    assert http1["url"] == "http://example.com/1"

    http2 = index.expect("HTTP")
    assert http2["url"] == "http://example.com/2"

    # Access second TIME
    time2 = index.expect("TIME")
    assert time2["ts"] == 2000

    # Now both types are exhausted
    with pytest.raises(ReplayDivergence) as exc:
        index.expect("HTTP")
    assert exc.value.code == "MISSING_DEP"


def test_replay_missing_dep(tmp_path):
    records = [{"seq": 1, "type": "HTTP"}]
    _write_transcripts(tmp_path, records)
    index = load_transcripts(tmp_path)
    index.expect("HTTP")
    with pytest.raises(ReplayDivergence) as exc:
        index.expect("HTTP")
    assert exc.value.code == "MISSING_DEP"
