"""Unit tests for module B landing-video risk evaluation.

The production module imports `config` from auto_put_ad_mini, which pulls the
full agent runtime. These tests inject a minimal config module so the pure risk
mapping logic can be tested without external services or optional dependencies.
"""

import importlib
import sys
import types
import unittest


def _load_video_risk_with_fake_config(max_allowed_level: int = 1):
    fake_config = types.ModuleType("config")
    fake_config.VIDEO_RISK_API_TIMEOUT_SECONDS = 10
    fake_config.VIDEO_RISK_API_URL = "https://example.invalid/video-risk"
    fake_config.VIDEO_RISK_CHECK_ENABLED = True
    fake_config.VIDEO_RISK_MAX_ALLOWED_LEVEL = max_allowed_level
    fake_config.VIDEO_RISK_TAG_LEVELS = {
        "85856": 1,
        "85862": 2,
        "85863": 3,
        "85864": 4,
        "85865": 5,
        "85866": 6,
        "85867": 7,
        "85868": 8,
        "85869": 9,
        "85870": 10,
    }

    old_config = sys.modules.get("config")
    sys.modules["config"] = fake_config
    sys.modules.pop("examples.auto_put_ad_mini.tools.video_risk", None)
    try:
        return importlib.import_module("examples.auto_put_ad_mini.tools.video_risk")
    finally:
        if old_config is None:
            sys.modules.pop("config", None)
        else:
            sys.modules["config"] = old_config


class VideoRiskEvaluationTest(unittest.TestCase):
    def test_level_one_passes_when_threshold_is_one(self):
        video_risk = _load_video_risk_with_fake_config(max_allowed_level=1)
        result = video_risk.evaluate_video_risk(123, ["85856"])
        self.assertTrue(result.passed)
        self.assertEqual(result.max_level, 1)

    def test_level_two_is_blocked_when_threshold_is_one(self):
        video_risk = _load_video_risk_with_fake_config(max_allowed_level=1)
        result = video_risk.evaluate_video_risk(123, ["85862"])
        self.assertFalse(result.passed)
        self.assertEqual(result.max_level, 2)

    def test_sample_level_seven_is_blocked(self):
        video_risk = _load_video_risk_with_fake_config(max_allowed_level=1)
        result = video_risk.evaluate_video_risk(71187017, ["85867", "85967", "88404"])
        self.assertFalse(result.passed)
        self.assertEqual(result.max_level, 7)
        self.assertEqual(result.risk_tag_ids, ["85867"])
        self.assertEqual(result.unknown_tag_ids, ["85967", "88404"])

    def test_unknown_tags_do_not_block_by_default(self):
        video_risk = _load_video_risk_with_fake_config(max_allowed_level=1)
        result = video_risk.evaluate_video_risk(123, ["99999"])
        self.assertTrue(result.passed)
        self.assertEqual(result.max_level, 0)
        self.assertEqual(result.unknown_tag_ids, ["99999"])


if __name__ == "__main__":
    unittest.main()
