"""Tests for native reproduction helpers (path normalization, pytest commands, case files)."""

from __future__ import annotations

from evals.importers.native_repro_helpers import (
    normalize_native_pytest_command,
    normalize_relative_path,
    write_native_case_files,
)
from llmdebug import _json as json


def test_normalize_relative_path_rejects_unsafe_values() -> None:
    assert normalize_relative_path("src/demo.py") == "src/demo.py"
    assert normalize_relative_path("./src/demo.py") == "src/demo.py"
    assert normalize_relative_path("../demo.py") is None
    assert normalize_relative_path("/abs/path.py") is None


def test_normalize_native_pytest_command_supported_forms() -> None:
    first = normalize_native_pytest_command("pytest -q tests/test_a.py::test_x")
    second = normalize_native_pytest_command("python -m pytest tests/test_b.py")
    third = normalize_native_pytest_command("pytest -q tests/")

    assert first is not None
    assert first.python_args == ["-m", "pytest", "-q", "tests/test_a.py::test_x"]
    assert first.test_paths == ["tests/test_a.py"]

    assert second is not None
    assert second.python_args == ["-m", "pytest", "tests/test_b.py"]
    assert second.source_test_selector == "tests/test_b.py"

    assert third is not None
    assert third.python_args == ["-m", "pytest", "-q", "tests/"]
    assert third.test_paths == ["tests"]


def test_normalize_native_pytest_command_rejects_shell_wrappers() -> None:
    assert normalize_native_pytest_command("pipenv run pytest -- tests/test_a.py") is None
    assert normalize_native_pytest_command("pytest tests/test_a.py && echo done") is None
    assert normalize_native_pytest_command("pytest") is None
    assert normalize_native_pytest_command("pytest -k expr") is None


def test_write_native_case_files_writes_contract_placeholder(tmp_path) -> None:
    case_dir = tmp_path / "case"
    write_native_case_files(
        case_dir,
        buggy_files={"src/demo.py": "x = 1\n"},
        test_files={"tests/test_demo.py": "def test_demo():\n    assert True\n"},
        oracle_patch="diff --git a/src/demo.py b/src/demo.py\n",
        metadata={"category": "logic_error"},
    )

    assert (case_dir / "src" / "demo.py").exists()
    assert (case_dir / "tests" / "test_demo.py").exists()
    assert (case_dir / "test_buggy.py").exists()
    assert (
        json.loads((case_dir / "case.json").read_text(encoding="utf-8"))["category"]
        == "logic_error"
    )
