"""AGBAgent — Allgemeine Geschäftsbedingungen (§§ 305 ff. BGB).

ChecklistAgent-Subclass: erst L1/L2-Keyword-Pass, dann **C-lean-Routing** — die
keyword-durchgefallenen Items werden per `decision_method` an die wiederverwendbare
Prüfer-Library geroutet (Embedding / Reference / LLM), davor das Geschäftsmodell-
Gate (Applicability), danach Severity-Re-Tiering (LOW → Empfehlung).
Validiert gegen 7-Firmen-Opus-GT: 71 % FP → ~0. Config in `_routing`, Flow in `_pipeline`.
"""

from __future__ import annotations

from compliance.services.doc_checks.agb_checks import AGB_CHECKLIST

from .._base import AgentInput, AgentOutput, lint_output
from .._checklist_agent import ChecklistAgent
from .._rollup import rollup
from ._pipeline import run_routed


class AGBAgent(ChecklistAgent):
    CHECKLIST = AGB_CHECKLIST
    agent_id = "agb"
    agent_version = "2.0"  # v2: decision_method-Routing (Embedding/Reference/LLM)
    doc_type = "agb"
    owned_mc_ids = tuple(c["id"] for c in AGB_CHECKLIST)

    async def evaluate(self, agent_input: AgentInput) -> AgentOutput:
        # 1) Basis-Keyword-Pass (L1/L2). out.findings = keyword-durchgefallene Items.
        out = await super().evaluate(agent_input)
        text = (agent_input.text or "").strip()
        if len(text) < 100 or not out.findings:
            return out  # zu kurz / nichts zu routen

        # 2) Routing: Gate + Embedding/Reference/LLM-Rescue der Keyword-Misses.
        kept, resolved, gated = await run_routed(
            out.findings, text, agent_input.context)
        resolved_set, gated_set = set(resolved), set(gated)

        # 3) Coverage angleichen: rescued → ok, gated → na.
        for c in out.mc_coverage:
            if c.mc_id in resolved_set:
                c.status, c.reason = "ok", "semantisch vorhanden (Routing)"
            elif c.mc_id in gated_set:
                c.status, c.reason = "na", "für Geschäftsmodell nicht anwendbar"

        # 4) Severity-Re-Tiering: HIGH/MEDIUM = Findings, LOW = nur Empfehlung.
        out.findings = [f for f in kept if f.severity in ("HIGH", "MEDIUM")]
        out.recommendations = rollup(kept)

        # 5) Aggregat-Kennzahlen neu (Coverage hat sich verschoben).
        cov = out.mc_coverage
        out.mc_total = len(cov)
        out.mc_ok = sum(1 for c in cov if c.status == "ok")
        out.mc_na = sum(1 for c in cov if c.status == "na")
        out.mc_high = sum(1 for c in cov if c.status == "high")
        out.mc_medium = sum(1 for c in cov if c.status == "medium")
        out.mc_low = sum(1 for c in cov if c.status == "low")
        out.notes = ((out.notes + " · ") if out.notes else "") + \
            f"routed: {len(resolved)} rescued, {len(gated)} n/a"
        return lint_output(out)
