"""Tests für Cookie-Policy-Agent v3 — Delegation an die Main-Tool-Engine,
Sektor-Filter und Maßnahmen statt Fragen."""

from __future__ import annotations

import asyncio

from compliance.services.specialist_agents.cookie_policy import v3_engine
from compliance.services.specialist_agents.cookie_policy.agent import (
    _build_measure,
)


def _run(coro):
    return asyncio.get_event_loop().run_until_complete(coro)


def test_build_measure_is_imperative_not_question():
    m = _build_measure("Speicherdauer der Cookies", "TDDDG § 25")
    assert "?" not in m
    assert "ergänzen" in m.lower()
    assert "Rechtsgrundlage" in m


def test_build_measure_handles_empty_label():
    m = _build_measure("", "")
    assert "?" not in m
    assert m.strip() != ""


def test_cookie_v3_delegates_and_sector_filters(monkeypatch):
    """run_v3_pipeline lädt über die Main-Tool-Engine (cookie) und das
    Sektor-Gate entfernt GOV-MCs out-of-scope."""
    async def _fake_load(doc_type, db_url, limit, business_scope=None):
        assert doc_type == "cookie"
        return [
            {"control_id": "COOKIE-1-A1", "title": "Cookie-Kategorien",
             "regulation": "TDDDG", "article": "§ 25", "severity": "HIGH",
             "check_question": "Kategorien genannt?",
             "pass_criteria": '["Cookie Kategorien essentiell"]',
             "fail_criteria": "[]"},
            {"control_id": "GOV-9-A1", "title": "Behörden-Cookie",
             "regulation": "X", "article": "", "severity": "HIGH",
             "check_question": "Behörde?",
             "pass_criteria": '["Behörde Aufsicht"]',
             "fail_criteria": "[]"},
        ]
    monkeypatch.setattr(
        "compliance.services.rag_document_checker._load_controls",
        _fake_load,
    )

    async def _no_match(*a, **kw):
        return set()
    monkeypatch.setattr(
        "compliance.services.mc_embedding_matcher.embedding_match",
        _no_match, raising=False,
    )

    text = ("Diese Website verwendet Cookies. Cookie-Kategorien: "
            "essentiell, funktional. Speicherdauer und Zweck beschrieben. "
            ) * 4  # > 100 Zeichen
    results, telem = _run(
        v3_engine.run_v3_pipeline(text, business_scope=set()),
    )
    cids = {r["control_id"] for r in results}
    assert "GOV-9-A1" not in cids          # Sektor out-of-scope entfernt
    assert "COOKIE-1-A1" in cids           # cookie-MC bleibt
    assert telem["sector_dropped"] == 1
