import json
import os
from pathlib import Path

from liteguard.evaluation import evaluate_guard
from liteguard.types import Guard, Operator, Rule


def _fixture_path() -> Path:
    repo_root = os.environ.get("LITEGUARD_REPO_ROOT")
    if repo_root:
        return Path(repo_root) / "tests" / "conformance" / "evaluation_cases.json"
    return Path(__file__).resolve().parents[3] / "tests" / "conformance" / "evaluation_cases.json"


def _load_fixture_bundle() -> dict[str, object]:
    return json.loads(_fixture_path().read_text())


def _to_guard(spec: dict[str, object]) -> Guard:
    rules = [
        Rule(
            property_name=rule["property_name"],
            operator=Operator(rule["operator"]),
            values=list(rule["values"]),
            result=rule["result"],
            enabled=rule["enabled"],
        )
        for rule in spec["rules"]
    ]
    return Guard(
        name="test.guard",
        default_value=spec["default_value"],
        adopted=True,
        rate_limit_per_minute=0,
        rate_limit_properties=[],
        disable_measurement=False,
        rules=rules,
    )


def test_evaluation_conformance_fixtures():
    bundle = _load_fixture_bundle()
    assert bundle["version"] == 1

    for case in bundle["cases"]:
        guard = _to_guard(case["guard"])
        assert evaluate_guard(guard, case["properties"]) is case["expected"], case["name"]
