"""Storage-Inventory: Cookie vs. anderer Endgeräte-Speicher (§25 TDDDG)."""

from __future__ import annotations

from compliance.services.cookie_storage_inventory import (
    build_storage_inventory,
    dedupe_vendor_cookies,
    detect_storage_type,
    storage_transparency_finding,
)


def test_dedupe_vendor_cookies_removes_consent_phase_dupes():
    vendors = [{"name": "V", "cookies": [
        {"name": "_ga", "expiry": "2 Jahre"},
        {"name": "_ga", "expiry": "2 Jahre"},   # before/after_accept-Dublette
        {"name": "_GA", "expiry": "2 Jahre"},    # case-insensitiv
        {"name": "sid", "expiry": "Session"},
    ]}]
    out = dedupe_vendor_cookies(vendors)
    names = [c["name"] for c in out[0]["cookies"]]
    assert names == ["_ga", "sid"]              # 4 → 2 eindeutig


def test_framework_artifacts_not_cookies():
    assert detect_storage_type("ComponentDefStorage__MUTEX_X") == "framework_storage"
    assert detect_storage_type("GlobalValueProviders__MUTEX_Y") == "framework_storage"
    assert detect_storage_type("LSKey-c$CookieConsentPolicy") == "framework_storage"


def test_duration_text_signals_local_storage():
    assert detect_storage_type(
        "x", "Wird solange gespeichert, bis es durch den Nutzer in seinem "
             "Browser deaktiviert wird.") == "local_storage"
    # echte Cookies bleiben cookie:
    assert detect_storage_type("_ga", "2 Jahre") == "cookie"
    assert detect_storage_type("sess", "Session") == "cookie"


def test_inventory_counts_and_transparency_finding():
    vendors = [{"name": "Salesforce", "cookies": [
        {"name": "ComponentDefStorage__MUTEX_X", "expiry": "bis Nutzer deaktiviert"},
        {"name": "_ga", "expiry": "2 Jahre"},
        {"name": "BrowserId1", "expiry": "1 Jahr"},
    ]}]
    inv = build_storage_inventory(vendors)
    assert inv["total"] == 3
    assert inv["real_cookies"] == 2          # _ga + BrowserId1
    assert inv["other_storage"] == 1         # das Framework-Artefakt
    tf = storage_transparency_finding(inv)
    assert tf and tf["type"] == "storage_transparency"
    assert "§ 25" in tf["control"]["article"]
    # per_cookie-Map (für den Frontend-Storage-Filter): name_lower → Typ.
    pc = inv["per_cookie"]
    assert pc["componentdefstorage__mutex_x"] == "framework_storage"
    assert pc["_ga"] == "cookie"
    assert pc["browserid1"] == "cookie"


def test_no_finding_when_all_real_cookies():
    inv = build_storage_inventory(
        [{"name": "X", "cookies": [{"name": "_ga", "expiry": "2 Jahre"}]}])
    assert inv["other_storage"] == 0
    assert storage_transparency_finding(inv) is None
