"""Tests for B19 Cookie-Coherence-Check (Salesforce-as-essential)."""

from unittest.mock import patch

from compliance.services.cookie_coherence_check import (
    _is_essential_category,
    _is_marketing_category,
    _is_pseudo_purpose,
    check_cookie_coherence,
)


class TestCategoryHelpers:
    def test_essential_de(self):
        assert _is_essential_category("Erforderlich")
        assert _is_essential_category("technisch notwendig")

    def test_essential_en(self):
        assert _is_essential_category("Strictly Necessary")
        assert _is_essential_category("essential")

    def test_not_essential(self):
        assert not _is_essential_category("Marketing")
        assert not _is_essential_category("Analyse")

    def test_marketing(self):
        assert _is_marketing_category("marketing")
        assert _is_marketing_category("advertising")
        assert not _is_marketing_category("functional")


class TestPseudoPurpose:
    def test_explicit_floskel(self):
        assert _is_pseudo_purpose("Siehe dazugehörige Datenverarbeitung")
        assert _is_pseudo_purpose("see above")

    def test_too_short(self):
        assert _is_pseudo_purpose("Nutzung Cookie")

    def test_real_purpose(self):
        assert not _is_pseudo_purpose(
            "Speichert die anonymisierte Besucher-ID zur "
            "Unterscheidung über mehrere Sessions hinweg."
        )


class TestCheck:
    def _state(self, vendors):
        return {"cmp_vendors": vendors}

    def test_no_vendors_no_findings(self):
        assert check_cookie_coherence({}) == []

    def test_marketing_as_essential_high_finding(self):
        # Pinterest _pin_unauth is actual=marketing per KB
        state = self._state([{
            "name": "Pinterest",
            "category": "Erforderlich",
            "cookies": [{
                "name": "_pin_unauth",
                "category": "Erforderlich",
                "purpose": "Speichert technische Nutzerkennung dauerhaft",
                "duration": "1 Jahr",
            }],
        }])
        findings = check_cookie_coherence(state)
        mae = [f for f in findings if f["check_id"] == "COOKIE-COHERENCE-MAE-001"]
        assert len(mae) == 1
        assert mae[0]["severity"] == "HIGH"
        assert mae[0]["actual_category"] == "marketing"

    def test_essential_with_long_lifetime_finding(self):
        # Even if KB-classified as functional/essential, 1 Jahr in
        # "essential" is implausible.
        state = self._state([{
            "name": "Salesforce",
            "category": "Erforderlich",
            "cookies": [{
                "name": "guest_uuid_essential_abc123",
                "category": "Erforderlich",
                "purpose": "Speichert anonyme Session-Kennung über Browser hinweg",
                "duration": "1 Jahr",
            }],
        }])
        findings = check_cookie_coherence(state)
        life = [f for f in findings if f["check_id"] == "COOKIE-COHERENCE-LIFE-001"]
        assert len(life) == 1
        assert life[0]["severity"] == "MEDIUM"

    def test_pseudo_purpose_finding(self):
        state = self._state([{
            "name": "TestVendor",
            "category": "functional",
            "purpose": "irgendwas",
            "cookies": [{
                "name": "completely_made_up_cookie_xyz",
                "category": "functional",
                "purpose": "Siehe dazugehörige Datenverarbeitung",
                "duration": "session",
            }],
        }])
        findings = check_cookie_coherence(state)
        purp = [f for f in findings if f["check_id"] == "COOKIE-COHERENCE-PURP-001"]
        assert len(purp) == 1

    def test_duplicate_vendor_finding(self):
        # Salesforce in TWO different categories
        state = self._state([
            {"name": "Salesforce", "category": "Erforderlich",
             "cookies": [{"name": "a", "purpose": "konkreter Zweck Text mit vielen Worten"}]},
            {"name": "Salesforce Inc.", "category": "Marketing",
             "cookies": [{"name": "b", "purpose": "konkreter Zweck Text mit vielen Worten"}]},
        ])
        findings = check_cookie_coherence(state)
        dup = [f for f in findings if f["check_id"] == "COOKIE-COHERENCE-DUP-001"]
        assert len(dup) == 1

    def test_pseudo_purpose_suppressed_when_vendor_purpose_substantial(self):
        # If vendor-level purpose has substantial text, cookie inheriting
        # "Siehe dazugehörige Datenverarbeitung" is not flagged.
        state = self._state([{
            "name": "Salesforce",
            "category": "functional",
            "purpose": (
                "Salesforce CRM-System verarbeitet personenbezogene Daten "
                "im Auftrag zur Verwaltung der Kundenbeziehung über mehrere "
                "Touchpoints hinweg."
            ),
            "cookies": [{
                "name": "sf_session",
                "category": "functional",
                "purpose": "Siehe dazugehörige Datenverarbeitung",
                "duration": "session",
            }],
        }])
        findings = check_cookie_coherence(state)
        purp = [f for f in findings if f["check_id"] == "COOKIE-COHERENCE-PURP-001"]
        assert purp == []
