"""内部キーのマスク。"""

from __future__ import annotations

import logging

from app import logging_utils

from .conftest import INTERNAL_KEY


def test_registered_secret_is_scrubbed() -> None:
    logging_utils.register_secret(INTERNAL_KEY)
    text = f"upstream call failed with Authorization: Bearer {INTERNAL_KEY}"
    scrubbed = logging_utils.scrub(text)
    assert INTERNAL_KEY not in scrubbed
    assert logging_utils.REDACTED in scrubbed


def test_authorization_header_is_scrubbed_without_registration() -> None:
    """登録前でも Authorization の値は伏せる。"""

    text = "Authorization: Bearer abcdef0123456789 said no"
    scrubbed = logging_utils.scrub(text)
    assert "abcdef0123456789" not in scrubbed


def test_issued_key_pattern_is_scrubbed() -> None:
    text = "key sk-aig-AbCdEfGhIjKlMnOpQrStUvWxYz012345 leaked"
    assert "sk-aig-AbCdEfGhIjKlMnOpQrStUvWxYz012345" not in logging_utils.scrub(text)


def test_json_secret_field_is_scrubbed() -> None:
    text = '{"api_key": "abcdef0123456789", "model": "qwen3-8b"}'
    scrubbed = logging_utils.scrub(text)
    assert "abcdef0123456789" not in scrubbed
    assert "qwen3-8b" in scrubbed


def test_short_values_are_not_registered() -> None:
    logging_utils.register_secret("abc")
    assert "abc" not in logging_utils.registered_secrets()


def test_mask_value() -> None:
    assert logging_utils.mask_value("sk-aig-abcdefgh1234") == "sk-a****1234"
    assert logging_utils.mask_value("short") == "****"
    assert logging_utils.mask_value("") == ""


def test_contains_secret_and_scrub_bytes() -> None:
    logging_utils.register_secret(INTERNAL_KEY)
    payload = f'{{"error":"bad token {INTERNAL_KEY}"}}'.encode()
    assert logging_utils.contains_secret(payload)
    scrubbed = logging_utils.scrub_bytes(payload)
    assert INTERNAL_KEY.encode() not in scrubbed


def test_scrub_bytes_handles_binary() -> None:
    logging_utils.register_secret(INTERNAL_KEY)
    payload = b"\xff\xfe" + INTERNAL_KEY.encode()
    assert INTERNAL_KEY.encode() not in logging_utils.scrub_bytes(payload)


def test_safe_headers_masks_credentials() -> None:
    masked = logging_utils.safe_headers(
        {"Authorization": "Bearer secret-value", "X-Control-Token": "t", "Accept": "*/*"}
    )
    assert masked["Authorization"] == logging_utils.REDACTED
    assert masked["X-Control-Token"] == logging_utils.REDACTED
    assert masked["Accept"] == "*/*"


def test_logging_filter_scrubs_records(caplog) -> None:
    logging_utils.register_secret(INTERNAL_KEY)
    logger = logging.getLogger("test-scrub")
    logger.addFilter(logging_utils.ScrubbingFilter())
    with caplog.at_level(logging.WARNING, logger="test-scrub"):
        logger.warning("failed with %s", INTERNAL_KEY)
    assert INTERNAL_KEY not in caplog.text
