"""
CRA Annex I — Essential Cybersecurity Requirements (40 Controls)

Quelle: Migration 059_wiki_cra_annex_i_detail.sql (Wiki-Artikel) +
        ai-compliance-sdk/internal/iace/measures_library_cra.go (M540-M548).

Statische Daten — eine deterministische Quelle fuer die /requirements und
/backlog Endpoints. KEINE LLM-Calls.

Schluesselfelder:
- req_id        eindeutige Stable-ID (CRA-AI-1 .. CRA-AI-40)
- category      eine der 8 Annex-I-Kategorien
- annex_anchor  Verweis auf CRA Annex I Punkt (z.B. "Annex I, 1(3)(d)")
- severity      CRITICAL | HIGH | MEDIUM | LOW — wie kritisch die Luecke ist
- iso27001_ref  Annex A Mapping zur ISO 27001:2022
- mapped_measures  Liste von M-IDs aus measures_library_cra.go
- evidence_type code | process | hybrid | document — wie pruefbar
- effort_days   Schaetzung in Personentagen fuer typische Umsetzung
"""

ANNEX_I_REQUIREMENTS = [
    # Part 1 — Produktsicherheit
    # Kategorie 1: Secure-by-Design
    {"req_id": "CRA-AI-1", "n": 1, "category": "Secure-by-Design",
     "title": "Secure-by-Default-Konfiguration",
     "annex_anchor": "Annex I, 1(1)", "iso27001_ref": ["A.8.9"],
     "description": "Produkte muessen mit sicheren Standardeinstellungen ausgeliefert werden. Keine offenen Ports, keine aktivierten Debug-Schnittstellen, keine unnoetig laufenden Dienste.",
     "severity": "HIGH", "mapped_measures": ["M545"], "evidence_type": "hybrid", "effort_days": 5},
    {"req_id": "CRA-AI-2", "n": 2, "category": "Secure-by-Design",
     "title": "Minimale Angriffsflaeche",
     "annex_anchor": "Annex I, 1(2)", "iso27001_ref": ["A.8.9", "A.8.20"],
     "description": "Nur notwendige Schnittstellen, Dienste und Protokolle aktivieren.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "code", "effort_days": 4},
    {"req_id": "CRA-AI-3", "n": 3, "category": "Secure-by-Design",
     "title": "Sichere Systemarchitektur",
     "annex_anchor": "Annex I, 1(3)", "iso27001_ref": ["A.8.27"],
     "description": "Sicherheitskritische Komponenten muessen isoliert werden (Sandboxing, Containerisierung, Privilege Separation).",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "code", "effort_days": 10},
    {"req_id": "CRA-AI-4", "n": 4, "category": "Secure-by-Design",
     "title": "Least-Privilege-Prinzip",
     "annex_anchor": "Annex I, 1(3)(d)", "iso27001_ref": ["A.8.2", "A.8.3"],
     "description": "Jede Komponente, jeder Prozess und jeder Benutzer erhaelt nur die minimal notwendigen Berechtigungen.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "code", "effort_days": 5},
    {"req_id": "CRA-AI-5", "n": 5, "category": "Secure-by-Design",
     "title": "Manipulationsschutz",
     "annex_anchor": "Annex I, 1(3)(c)", "iso27001_ref": ["A.8.24"],
     "description": "Schutz vor unautorisierter Aenderung von Software und Konfiguration (Code Signing, Secure Boot, TPM).",
     "severity": "HIGH", "mapped_measures": ["M541"], "evidence_type": "code", "effort_days": 8},
    {"req_id": "CRA-AI-6", "n": 6, "category": "Secure-by-Design",
     "title": "Integritaetspruefung",
     "annex_anchor": "Annex I, 1(3)(c)", "iso27001_ref": ["A.8.24"],
     "description": "Automatische Ueberpruefung der Integritaet von Software, Firmware und Konfigurationsdaten bei Start und Laufzeit.",
     "severity": "HIGH", "mapped_measures": ["M547"], "evidence_type": "code", "effort_days": 4},
    # Kategorie 2: Auth
    {"req_id": "CRA-AI-7", "n": 7, "category": "Authentifizierung",
     "title": "Starke Authentifizierung",
     "annex_anchor": "Annex I, 1(3)(d)", "iso27001_ref": ["A.8.5"],
     "description": "Sichere Authentifizierungsmechanismen, MFA fuer administrative Zugriffe, FIDO2/WebAuthn.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "code", "effort_days": 6},
    {"req_id": "CRA-AI-8", "n": 8, "category": "Authentifizierung",
     "title": "Keine Default-Passwoerter",
     "annex_anchor": "Annex I, 1(3)(d)", "iso27001_ref": ["A.8.5"],
     "description": "Produkte duerfen keine universellen Standardpasswoerter verwenden. Aenderung bei Ersteinrichtung erzwingen.",
     "severity": "CRITICAL", "mapped_measures": ["M542"], "evidence_type": "code", "effort_days": 2},
    {"req_id": "CRA-AI-9", "n": 9, "category": "Authentifizierung",
     "title": "Sicheres Credential-Management",
     "annex_anchor": "Annex I, 1(3)(d)", "iso27001_ref": ["A.8.5"],
     "description": "Zugangsdaten verschluesselt speichern (bcrypt, Argon2id). Keine Klartextspeicherung. Tokens rotieren.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "code", "effort_days": 3},
    {"req_id": "CRA-AI-10", "n": 10, "category": "Authentifizierung",
     "title": "Sitzungsmanagement",
     "annex_anchor": "Annex I, 1(3)(d)", "iso27001_ref": ["A.8.5"],
     "description": "Session-Verwaltung mit Timeout, Token-Binding, Invalidierung bei Logout. CSRF-Schutz.",
     "severity": "MEDIUM", "mapped_measures": [], "evidence_type": "code", "effort_days": 3},
    {"req_id": "CRA-AI-11", "n": 11, "category": "Authentifizierung",
     "title": "Brute-Force-Schutz",
     "annex_anchor": "Annex I, 1(3)(d)", "iso27001_ref": ["A.8.5", "A.8.16"],
     "description": "Schutz vor Brute-Force und Credential-Stuffing via Rate Limiting, Account Lockout, CAPTCHA.",
     "severity": "MEDIUM", "mapped_measures": [], "evidence_type": "code", "effort_days": 2},
    {"req_id": "CRA-AI-12", "n": 12, "category": "Authentifizierung",
     "title": "Rollenbasierte Autorisierung",
     "annex_anchor": "Annex I, 1(3)(d)", "iso27001_ref": ["A.8.2", "A.8.3"],
     "description": "RBAC implementieren. Trennung administrativ vs Nutzer. Least-Privilege durchsetzen.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "code", "effort_days": 4},
    # Kategorie 3: Krypto
    {"req_id": "CRA-AI-13", "n": 13, "category": "Kryptografie",
     "title": "Verschluesselung sensibler Daten",
     "annex_anchor": "Annex I, 1(3)(e)", "iso27001_ref": ["A.8.24"],
     "description": "Sensible Daten at rest (AES-256) und in transit (TLS 1.2+) verschluesseln.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "code", "effort_days": 4},
    {"req_id": "CRA-AI-14", "n": 14, "category": "Kryptografie",
     "title": "Speicher-Schutz (Data at Rest)",
     "annex_anchor": "Annex I, 1(3)(e)", "iso27001_ref": ["A.8.24"],
     "description": "Verschluesselung von Festplatten, Datenbanken, Backups. Schluessel getrennt von Daten.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "code", "effort_days": 3},
    {"req_id": "CRA-AI-15", "n": 15, "category": "Kryptografie",
     "title": "Transport-Schutz (Data in Transit)",
     "annex_anchor": "Annex I, 1(3)(e)", "iso27001_ref": ["A.8.24"],
     "description": "TLS 1.2+ fuer alle Netzwerkkommunikation. SSL/TLS 1.0/1.1 deaktivieren. Certificate Pinning.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "code", "effort_days": 2},
    {"req_id": "CRA-AI-16", "n": 16, "category": "Kryptografie",
     "title": "Sicheres Schluesselmanagement",
     "annex_anchor": "Annex I, 1(3)(e)", "iso27001_ref": ["A.8.24"],
     "description": "Schluessel in HSM/Vault. Mind. jaehrliche Rotation. Dokumentation der Lebenszyklen.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "hybrid", "effort_days": 8},
    {"req_id": "CRA-AI-17", "n": 17, "category": "Kryptografie",
     "title": "Datenminimierung",
     "annex_anchor": "Annex I, 1(3)(f)", "iso27001_ref": ["A.8.10", "A.8.11"],
     "description": "Nur Daten erfassen, die fuer die Produktfunktion erforderlich sind. DSGVO-Grundsaetze beachten.",
     "severity": "MEDIUM", "mapped_measures": [], "evidence_type": "process", "effort_days": 3},
    # Kategorie 4: SSDLC
    {"req_id": "CRA-AI-18", "n": 18, "category": "SSDLC",
     "title": "Strukturierter SSDLC",
     "annex_anchor": "Annex I, 1(1)", "iso27001_ref": ["A.8.25", "A.8.26"],
     "description": "Formaler Secure Software Development Lifecycle mit Security Gates in jeder Phase.",
     "severity": "MEDIUM", "mapped_measures": [], "evidence_type": "process", "effort_days": 15},
    {"req_id": "CRA-AI-19", "n": 19, "category": "SSDLC",
     "title": "Systematische Code Reviews",
     "annex_anchor": "Annex I, 1(1)", "iso27001_ref": ["A.8.25"],
     "description": "Peer Reviews mit Security-Fokus fuer jeden Commit. OWASP Top 10 + CWE Top 25 Checklisten.",
     "severity": "MEDIUM", "mapped_measures": [], "evidence_type": "process", "effort_days": 5},
    {"req_id": "CRA-AI-20", "n": 20, "category": "SSDLC",
     "title": "Automatisierte Sicherheitstests",
     "annex_anchor": "Annex I, 1(1)", "iso27001_ref": ["A.8.25"],
     "description": "SAST, DAST, SCA und Secrets Detection in der CI/CD-Pipeline.",
     "severity": "HIGH", "mapped_measures": ["M548"], "evidence_type": "code", "effort_days": 8},
    # Kategorie 5: Supply Chain & SBOM
    {"req_id": "CRA-AI-21", "n": 21, "category": "Supply Chain",
     "title": "Supply-Chain-Security",
     "annex_anchor": "Annex I, 1(5)", "iso27001_ref": ["A.5.19", "A.5.21"],
     "description": "Drittanbieter-Komponenten systematisch auf Schwachstellen und Lizenz-Compliance pruefen.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "process", "effort_days": 5},
    {"req_id": "CRA-AI-22", "n": 22, "category": "Supply Chain",
     "title": "Dependency-Monitoring",
     "annex_anchor": "Annex I, 1(5)", "iso27001_ref": ["A.8.8", "A.8.25"],
     "description": "Kontinuierliche CVE-Ueberwachung aller Abhaengigkeiten. Automatische Benachrichtigungen.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "code", "effort_days": 3},
    {"req_id": "CRA-AI-23", "n": 23, "category": "Supply Chain",
     "title": "Software Bill of Materials (SBOM)",
     "annex_anchor": "Annex I, 1(5)", "iso27001_ref": ["A.8.25"],
     "description": "Maschinenlesbares SBOM (CycloneDX oder SPDX). Top-Level-Abhaengigkeiten mit Name, Version, Lizenz. Bei jedem Release aktualisieren.",
     "severity": "CRITICAL", "mapped_measures": ["M540"], "evidence_type": "code", "effort_days": 2},
    # Kategorie 6: Logging & Monitoring
    {"req_id": "CRA-AI-24", "n": 24, "category": "Logging",
     "title": "Security-Logging",
     "annex_anchor": "Annex I, 1(3)(g)", "iso27001_ref": ["A.8.15"],
     "description": "Logs aller sicherheitsrelevanten Ereignisse: Login, Berechtigungen, Admin-Aktionen, APIs, Fehler.",
     "severity": "MEDIUM", "mapped_measures": [], "evidence_type": "code", "effort_days": 4},
    {"req_id": "CRA-AI-25", "n": 25, "category": "Logging",
     "title": "Ereignis-Monitoring",
     "annex_anchor": "Annex I, 1(3)(g)", "iso27001_ref": ["A.8.16"],
     "description": "Zentrale Sammlung und Echtzeit-Ueberwachung. SIEM oder vergleichbares. Event-Korrelation.",
     "severity": "MEDIUM", "mapped_measures": [], "evidence_type": "process", "effort_days": 10},
    {"req_id": "CRA-AI-26", "n": 26, "category": "Logging",
     "title": "Anomalie-Erkennung",
     "annex_anchor": "Annex I, 1(3)(g)", "iso27001_ref": ["A.8.16"],
     "description": "Automatische Erkennung von Angriffsmustern. Alarmierung bei Baseline-Abweichungen. Threat Intel.",
     "severity": "MEDIUM", "mapped_measures": [], "evidence_type": "process", "effort_days": 8},
    {"req_id": "CRA-AI-27", "n": 27, "category": "Logging",
     "title": "Log-Integritaet und -Aufbewahrung",
     "annex_anchor": "Annex I, 1(3)(g)", "iso27001_ref": ["A.8.15"],
     "description": "Manipulationssichere Logs (append-only, signiert oder WORM). Mind. 12 Monate Aufbewahrung.",
     "severity": "MEDIUM", "mapped_measures": [], "evidence_type": "code", "effort_days": 4},
    # Kategorie 7: Updates
    {"req_id": "CRA-AI-28", "n": 28, "category": "Updates",
     "title": "Sichere Update-Mechanismen",
     "annex_anchor": "Annex I, 1(4)", "iso27001_ref": ["A.8.8", "A.8.19"],
     "description": "Updates ueber sichere Kanaele (HTTPS, signiert). Automatische oder einfach zugaengliche Update-Moeglichkeit. Rollback-Faehigkeit.",
     "severity": "HIGH", "mapped_measures": ["M541", "M547"], "evidence_type": "code", "effort_days": 8},
    {"req_id": "CRA-AI-29", "n": 29, "category": "Updates",
     "title": "Update-Authentizitaet",
     "annex_anchor": "Annex I, 1(4)", "iso27001_ref": ["A.8.24"],
     "description": "Updates digital signiert. Signaturpruefung vor Installation. Dokumentierte Key Ceremony.",
     "severity": "CRITICAL", "mapped_measures": ["M541"], "evidence_type": "code", "effort_days": 3},
    {"req_id": "CRA-AI-30", "n": 30, "category": "Updates",
     "title": "Update-Integritaet",
     "annex_anchor": "Annex I, 1(4)", "iso27001_ref": ["A.8.24"],
     "description": "Integritaetspruefung jedes Update-Pakets (Hash, Signatur). Manipulationen waehrend Uebertragung erkennen.",
     "severity": "HIGH", "mapped_measures": ["M547"], "evidence_type": "code", "effort_days": 2},
    {"req_id": "CRA-AI-31", "n": 31, "category": "Updates",
     "title": "Lifecycle-Support",
     "annex_anchor": "Annex I, 1(4)", "iso27001_ref": ["A.8.8"],
     "description": "Security-Updates fuer mind. 5 Jahre ab Inverkehrbringen oder erwartete Nutzungsdauer. End-of-Life klar kommunizieren.",
     "severity": "HIGH", "mapped_measures": ["M544"], "evidence_type": "process", "effort_days": 3},
    # Part 2 — Vulnerability Handling
    {"req_id": "CRA-AI-32", "n": 32, "category": "Vulnerability Handling",
     "title": "Schwachstellen-Identifikation",
     "annex_anchor": "Annex I, 2(1)", "iso27001_ref": ["A.8.8"],
     "description": "Kontinuierliches CVE-Monitoring aller eingesetzten Komponenten. Bug Bounty oder Responsible Disclosure.",
     "severity": "HIGH", "mapped_measures": [], "evidence_type": "process", "effort_days": 4},
    {"req_id": "CRA-AI-33", "n": 33, "category": "Vulnerability Handling",
     "title": "SBOM-Pflege und Analyse",
     "annex_anchor": "Annex I, 2(1)", "iso27001_ref": ["A.8.8", "A.8.25"],
     "description": "SBOM aktuell halten und kontinuierlich gegen CVE-Datenbanken pruefen. Auto-Alarmierung bei neuen CVEs.",
     "severity": "HIGH", "mapped_measures": ["M540"], "evidence_type": "code", "effort_days": 3},
    {"req_id": "CRA-AI-34", "n": 34, "category": "Vulnerability Handling",
     "title": "Risikobasierte Priorisierung",
     "annex_anchor": "Annex I, 2(2)", "iso27001_ref": ["A.8.8"],
     "description": "CVSS-basierte Priorisierung. SLAs: Kritisch 24-72h, Hoch 7 Tage, Mittel 30 Tage, Niedrig naechster Zyklus.",
     "severity": "HIGH", "mapped_measures": ["M544"], "evidence_type": "process", "effort_days": 2},
    {"req_id": "CRA-AI-35", "n": 35, "category": "Vulnerability Handling",
     "title": "Coordinated Vulnerability Disclosure",
     "annex_anchor": "Annex I, 2(5)", "iso27001_ref": ["A.5.5", "A.5.6"],
     "description": "CVD-Policy mit Meldeprozess. Kontaktadresse fuer Forscher. Eingangsbestaetigung innerhalb 5 Werktagen.",
     "severity": "CRITICAL", "mapped_measures": ["M543"], "evidence_type": "document", "effort_days": 2},
    {"req_id": "CRA-AI-36", "n": 36, "category": "Vulnerability Handling",
     "title": "Incident-Response-Prozess",
     "annex_anchor": "Annex I, 2(5)", "iso27001_ref": ["A.5.24", "A.5.25", "A.5.26"],
     "description": "Dokumentierter Prozess: Detection -> Classification -> Containment -> Investigation -> Recovery -> Reporting -> Lessons Learned.",
     "severity": "HIGH", "mapped_measures": ["M546"], "evidence_type": "process", "effort_days": 10},
    {"req_id": "CRA-AI-37", "n": 37, "category": "Vulnerability Handling",
     "title": "Fruehwarnung (24h)",
     "annex_anchor": "Annex I, 2(7) + Art. 14(2)(a)", "iso27001_ref": ["A.5.24", "A.5.26"],
     "description": "Bei aktiv ausgenutzten Schwachstellen oder schweren Vorfaellen: Fruehwarnung an ENISA/CSIRT innerhalb 24 Stunden.",
     "severity": "CRITICAL", "mapped_measures": ["M546"], "evidence_type": "process", "effort_days": 3},
    {"req_id": "CRA-AI-38", "n": 38, "category": "Vulnerability Handling",
     "title": "Detaillierter Vorfallsbericht (72h)",
     "annex_anchor": "Annex I, 2(7) + Art. 14(2)(b)", "iso27001_ref": ["A.5.24", "A.5.26"],
     "description": "72h: Detaillierter Bericht mit Umfang, Auswirkung, Ursachenanalyse, Gegenmassnahmen. Bei personenbezogenen Daten zusaetzlich DSGVO Art. 33/34.",
     "severity": "CRITICAL", "mapped_measures": ["M546"], "evidence_type": "process", "effort_days": 2},
    {"req_id": "CRA-AI-39", "n": 39, "category": "Vulnerability Handling",
     "title": "Patch-Bereitstellung",
     "annex_anchor": "Annex I, 2(3)", "iso27001_ref": ["A.8.8"],
     "description": "Patches fuer gemeldete Schwachstellen so schnell wie moeglich. Security Advisories (CSAF-Format empfohlen).",
     "severity": "HIGH", "mapped_measures": ["M544"], "evidence_type": "process", "effort_days": 5},
    {"req_id": "CRA-AI-40", "n": 40, "category": "Vulnerability Handling",
     "title": "Dokumentation und Nachbereitung",
     "annex_anchor": "Annex I, 2(6)", "iso27001_ref": ["A.5.27"],
     "description": "Lueckenlose Dokumentation aller Schwachstellen + Vorfaelle, mind. 10 Jahre Aufbewahrung. Lessons-Learned-Prozess.",
     "severity": "MEDIUM", "mapped_measures": [], "evidence_type": "document", "effort_days": 3},
]

# Measure descriptions (from measures_library_cra.go)
MEASURES = {
    "M540": "Software Bill of Materials (SBOM) erstellen und mit der Maschine ausliefern",
    "M541": "Signierte Software- und Firmware-Updates mit Rollback-Schutz",
    "M542": "Initiale Default-Passwoerter beim ersten Start erzwungen aendern",
    "M543": "CVD-Policy (Coordinated Vulnerability Disclosure) veroeffentlichen",
    "M544": "Patch-SLA mit Severity-Tiers dokumentieren",
    "M545": "Cybersecurity-Hardening-Guide fuer den Anwender beilegen",
    "M546": "Incident-Meldeprozess an ENISA / nationale CSIRT definieren",
    "M547": "Updates ueber authentisierten Kanal mit Integritaetspruefung",
    "M548": "Sicherheitsbewertung / Penetrationstest vor Inverkehrbringen",
}

# CRA-Deadlines (deterministisch, kein DB-Lookup)
DEADLINES = [
    {"date": "2026-06-11", "label": "Conformity Bodies benannt"},
    {"date": "2026-09-11", "label": "Vulnerability-Reporting-Pflicht aktiv (24h/72h)"},
    {"date": "2027-12-11", "label": "CE-Marking nach CRA verpflichtend"},
]


# Severity-Gewichtung fuer Priority-Score
SEVERITY_WEIGHT = {
    "CRITICAL": 100,
    "HIGH": 60,
    "MEDIUM": 30,
    "LOW": 10,
}


# ── Kuratierte Maßnahmen-Bibliothek (Source of Truth: data/measures_curated.json) ──
# Deduplizierte, standard-gestützte Maßnahmen. Beim Import: MEASURES (id->Name) wird
# Superset, MEASURE_DETAILS trägt den Volltext, und jede CRA-Anforderung bekommt
# mapped_measures aus dem `covers`-Feld. Defensiv: bei fehlender/kaputter JSON bleibt
# das hartkodierte 9er-Set + Mapping erhalten.
import json as _json
import os as _os

from compliance.data.norm_sources import classify_refs as _classify_refs

MEASURE_DETAILS: dict = {}

try:
    _MEAS_PATH = _os.path.join(_os.path.dirname(__file__), "..", "data", "measures_curated.json")
    with open(_MEAS_PATH, encoding="utf-8") as _fh:
        _curated = _json.load(_fh)
    MEASURE_DETAILS = {m["id"]: m for m in _curated if m.get("id")}
    # Provenance: curated measures are expert/standards-based ('core' tier); each
    # norm_ref is license-classified (law/public/open vs paid-reference-only).
    for _m in MEASURE_DETAILS.values():
        _m.setdefault("tier", "core")
        _m.setdefault("provenance", "curated_expert_standards")
        _m["norm_sources"] = _classify_refs(_m.get("norm_refs", []))
    for _m in _curated:
        if _m.get("id") and _m.get("name"):
            MEASURES[_m["id"]] = _m["name"]
    _cover_map: dict = {}
    for _m in _curated:
        for _c in _m.get("covers", []):
            _cover_map.setdefault(_c, []).append(_m["id"])
    for _r in ANNEX_I_REQUIREMENTS:
        _ids = _cover_map.get(_r["req_id"])
        if _ids:
            _r["mapped_measures"] = _ids
except Exception:  # noqa: BLE001 — Bibliothek optional; Fallback = hartkodiertes Set
    pass
