"""Tests for security utilities — secret redaction, input sanitization."""

from __future__ import annotations

from agent_scout.security import redact_dict, redact_secrets, sanitize_log_message


def test_redact_openai_key():
    text = "My key is sk-abcdefghijklmnopqrstuvwxyz1234567890"
    result = redact_secrets(text)
    assert "sk-a[REDACTED]" in result
    assert "abcdefghijklmnopqrstuvwxyz" not in result


def test_redact_tavily_key():
    text = "Using tvly-abcdefghijklmnopqrstuvwxyz"
    result = redact_secrets(text)
    assert "tvly[REDACTED]" in result


def test_redact_api_key_pattern():
    text = "api_key = supersecretvalue12345"
    result = redact_secrets(text)
    assert "supersecretvalue" not in result


def test_redact_password_pattern():
    text = "password = mysecretpassword"
    result = redact_secrets(text)
    assert "mysecretpassword" not in result


def test_no_false_positive_on_normal_text():
    text = "This is a normal sentence about search results."
    result = redact_secrets(text)
    assert result == text


def test_redact_dict_sensitive_keys():
    data = {
        "name": "test",
        "api_key": "sk-1234567890abcdef",
        "tavily_api_key": "tvly-secret123456",
        "nested": {
            "password": "secret",
            "normal": "value",
        },
    }
    result = redact_dict(data)
    assert result["name"] == "test"
    assert "***" in result["api_key"]
    assert "***" in result["tavily_api_key"]
    assert "***" in result["nested"]["password"]
    assert result["nested"]["normal"] == "value"


def test_redact_dict_with_list():
    data = {
        "items": [
            {"name": "a", "token": "mytoken123"},
            {"name": "b", "value": "safe"},
        ]
    }
    result = redact_dict(data)
    assert "***" in result["items"][0]["token"]
    assert result["items"][1]["value"] == "safe"


def test_redact_dict_empty_sensitive_value():
    data = {"api_key": "", "name": "test"}
    result = redact_dict(data)
    assert result["api_key"] == ""  # Empty strings left alone


def test_redact_dict_depth_limit():
    # Build deeply nested dict
    data: dict = {"level": 0}
    current = data
    for i in range(15):
        current["nested"] = {"level": i + 1, "password": "secret"}
        current = current["nested"]

    result = redact_dict(data)
    assert result["level"] == 0  # Didn't crash


def test_sanitize_log_message():
    msg = "Calling API with key sk-abcdefghijklmnopqrstuvwxyz1234567890"
    result = sanitize_log_message(msg)
    assert "abcdefghijklmnopqrstuvwxyz" not in result


def test_redact_multiple_secrets_in_one_string():
    text = "key1=sk-aaaaaaaaaaaaaaaaaaaaaa key2=tvly-bbbbbbbbbbbbbbbbbbbbbb"
    result = redact_secrets(text)
    assert "aaaaaaaaaaaaaaaaaaa" not in result
    assert "bbbbbbbbbbbbbbbbbb" not in result
