"""Tests for YAML policy loading and overrides."""

import tempfile
import textwrap
from pathlib import Path

import pytest

from interceptor import Interceptor, RiskLevel
from interceptor.exceptions import PolicyLoadError
from interceptor.policy import PolicyEngine


def _write_policy(content: str) -> Path:
    """Write policy YAML to a temp file and return its path."""
    f = tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False)
    f.write(textwrap.dedent(content))
    f.flush()
    return Path(f.name)


def test_policy_overrides_tool_risk():
    path = _write_policy("""
        tools:
          safe_tool:
            risk: HIGH
    """)
    guard = Interceptor(mode="strict", policy_path=path)
    d = guard.run("safe_tool", {}, user_role="user")
    assert d.risk_level == RiskLevel.HIGH
    assert not d.allowed


def test_policy_extra_keywords():
    path = _write_policy("""
        keywords:
          - nuke
    """)
    guard = Interceptor(mode="strict", policy_path=path)
    d = guard.run("nuke_everything", {}, user_role="user")
    assert d.risk_level == RiskLevel.HIGH
    assert not d.allowed


def test_invalid_yaml_raises():
    f = tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False)
    f.write(": :\n  - [invalid")
    f.flush()
    engine = PolicyEngine()
    with pytest.raises(PolicyLoadError):
        engine.load(f.name)


def test_missing_file_raises():
    engine = PolicyEngine()
    with pytest.raises(PolicyLoadError, match="not found"):
        engine.load("/nonexistent/policy.yaml")


def test_policy_tool_and_keyword_combined():
    path = _write_policy("""
        tools:
          write_file:
            risk: HIGH
        keywords:
          - purge
    """)
    guard = Interceptor(mode="strict", policy_path=path)
    # Tool override
    d1 = guard.run("write_file", {"data": "x"}, user_role="user")
    assert d1.risk_level == RiskLevel.HIGH
