"""Policy clause mappings and impact helpers."""

from __future__ import annotations

from typing import Dict, List


# source_id -> list of rule-id prefixes that depend on the source.
SOURCE_RULE_PREFIXES: Dict[str, List[str]] = {
    "ios_app_store_review_guidelines": ["IOS-"],
    "apple_privacy_manifest": ["IOS-PRIV-", "IOS-ENT-"],
    "android_play_policy": ["AND-POL-", "AND-PERM-"],
    "android_target_sdk_requirements": ["AND-SDK-"],
    "owasp_top_10": ["WEB-OWASP-", "WEB-SEC-", "AND-SEC-", "IOS-SEC-"],
    "w3c_wcag_21": ["WEB-A11Y-", "CROSS-A11Y-"],
    "w3c_permissions_policy": ["WEB-SEC-"],
}

# Rule prefixes to canonical policy clause references.
POLICY_CLAUSE_BY_PREFIX: Dict[str, str] = {
    "IOS-PRIV-": "Apple App Store Review Guidelines 5.1 (Data Collection and Storage)",
    "IOS-SEC-": "Apple App Store Review Guidelines 2.5 (Software Requirements)",
    "IOS-ENT-": "Apple App Store Review Guidelines 2.5.1 (Public APIs and entitlements)",
    "AND-SDK-": "Google Play Target API Level Requirements",
    "AND-PERM-": "Google Play Permissions Policy",
    "AND-POL-": "Google Play Developer Program Policy",
    "WEB-OWASP-": "OWASP Top 10 (2021)",
    "WEB-A11Y-": "W3C WCAG 2.1",
    "WEB-SEC-": "OWASP Secure Headers / Browser Security Guidance",
    "CROSS-GDPR-": "GDPR Articles 6, 7, 13, 20, 37",
    "CROSS-COPPA-": "FTC COPPA Rule",
    "CROSS-HIPAA-": "HIPAA Security Rule",
    "CROSS-PCI-": "PCI DSS v4.0",
}


def policy_clause_for_rule(rule_id: str) -> str:
    rid = (rule_id or "").upper()
    for prefix, clause in POLICY_CLAUSE_BY_PREFIX.items():
        if rid.startswith(prefix):
            return clause
    return ""


def apply_policy_metadata(finding) -> None:
    if getattr(finding, "policy_clause", ""):
        return
    clause = policy_clause_for_rule(getattr(finding, "rule_id", ""))
    if clause:
        finding.policy_clause = clause


def impacted_rules_for_sources(source_ids: List[str], known_rule_ids: List[str]) -> List[str]:
    """Return likely impacted rule IDs for a list of changed policy source IDs."""
    out: List[str] = []
    for source_id in source_ids:
        prefixes = SOURCE_RULE_PREFIXES.get(source_id, [])
        for rid in known_rule_ids:
            if any(rid.startswith(p) for p in prefixes):
                out.append(rid)
    return sorted(set(out))
