"""Tests for RCA identity/signature helpers."""

from __future__ import annotations

from pathlib import Path

from llmdebug.rca_identity import build_failure_signature, derive_session_id


def test_derive_session_id_prefers_pytest_nodeid(tmp_path: Path) -> None:
    snapshot = {
        "name": "fallback_name",
        "pytest": {"nodeid": "tests/test_app.py::test_parse"},
        "exception": {"type": "ValueError", "message": "boom"},
        "frames": [],
        "crash_frame_index": 0,
    }

    session_id = derive_session_id(snapshot, out_dir=str(tmp_path), fallback="mcp")
    assert session_id.endswith("::tests/test_app.py::test_parse")


def test_derive_session_id_falls_back_to_snapshot_name(tmp_path: Path) -> None:
    snapshot = {
        "name": "test_case_alpha",
        "exception": {"type": "RuntimeError", "message": "boom"},
        "frames": [],
        "crash_frame_index": 0,
    }

    session_id = derive_session_id(snapshot, out_dir=str(tmp_path), fallback="mcp")
    assert session_id.endswith("::test_case_alpha")


def test_build_failure_signature_text_fallback_is_stable() -> None:
    stderr = "Traceback\nValueError: bad input"
    sig_a = build_failure_signature(None, stdout="", stderr=stderr)
    sig_b = build_failure_signature(None, stdout="", stderr=stderr)

    assert sig_a == sig_b
    assert sig_a.startswith("TextFailure:")


def test_build_failure_signature_handles_non_numeric_crash_line(tmp_path: Path) -> None:
    snapshot = {
        "exception": {"type": "ValueError", "message": "boom"},
        "frames": [{"file": "/code/app.py", "line": "?", "function": "parse_input"}],
        "crash_frame_index": 0,
    }

    signature = build_failure_signature(snapshot, stdout="", stderr="")

    assert signature.startswith("ValueError:")
