from __future__ import annotations

import json
from pathlib import Path

from autodebug_replay.canonicalize import body_hash, canonical_url, sql_fingerprint
from autodebug_replay.http_replay import _expect_http
from autodebug_replay.transcripts import TranscriptIndex


def test_fixture_http_volatile_payload_semantic_match():
    fixture_path = Path("tests/fixtures/replay/http_volatile_match.json")
    data = json.loads(fixture_path.read_text(encoding="utf-8"))

    content_type = data["content_type"]
    recorded_body = json.dumps(data["recorded_body"]).encode("utf-8")
    actual_body = json.dumps(data["actual_body"]).encode("utf-8")

    record = {
        "type": "HTTP",
        "seq": 1,
        "method": "POST",
        "url_canonical": canonical_url("https://example.com/users"),
        "body_hash": body_hash(recorded_body, content_type),
        "status": 200,
        "response_body_bytes": "ok",
        "response_body_encoding": "utf-8",
        "headers_canon": {"content-type": "application/json"},
        "request_body_bytes": recorded_body.decode("utf-8"),
        "request_body_encoding": "utf-8",
    }
    index = TranscriptIndex(records=[record])
    matched = _expect_http(
        index,
        "POST",
        "https://example.com/users",
        actual_body,
        content_type,
    )
    assert matched["seq"] == 1


def test_fixture_sql_order_equivalence_fingerprint_match():
    fixture_path = Path("tests/fixtures/replay/sql_order_equivalence.json")
    data = json.loads(fixture_path.read_text(encoding="utf-8"))
    expected_fp = sql_fingerprint(data["expected_sql"])
    actual_fp = sql_fingerprint(data["actual_sql"])
    assert expected_fp == actual_fp
