"""
Compliance mapping data types for violation-to-framework enrichment.
Created as part of WS4 Milestone 4A (DEV-1111).
"""

from dataclasses import dataclass, field

TIER_ORDER = {
    "free": 0,
    "pro": 1,
    "team": 2,
    "business": 3,
    "enterprise": 4,
}


@dataclass
class FrameworkControl:
    """A single framework control citation."""

    framework_id: str
    framework_name: str
    control_id: str
    control_title: str
    min_tier: str
    framework_url: str | None = None

    def to_dict(self) -> dict[str, str | None]:
        result: dict[str, str | None] = {
            "framework_id": self.framework_id,
            "framework_name": self.framework_name,
            "control_id": self.control_id,
            "control_title": self.control_title,
            "min_tier": self.min_tier,
        }
        if self.framework_url:
            result["framework_url"] = self.framework_url
        return result


@dataclass
class ControlMapping:
    """All framework mappings for a single rule_id."""

    rule_id: str
    cwe_ids: list[str] = field(default_factory=list)
    controls: list[FrameworkControl] = field(default_factory=list)

    def controls_for_tier(self, tier: str) -> list[FrameworkControl]:
        """Return controls visible at the given tier."""
        tier_rank = TIER_ORDER.get(tier, 0)
        return [c for c in self.controls if TIER_ORDER.get(c.min_tier, 0) <= tier_rank]


@dataclass
class MappingRegistry:
    """Complete mapping registry loaded from JSON."""

    version: str
    updated: str
    mappings: dict[str, ControlMapping] = field(default_factory=dict)

    def get_controls(self, rule_id: str, tier: str = "free") -> list[FrameworkControl]:
        """Get framework controls for a rule_id filtered by tier."""
        mapping = self.mappings.get(rule_id)
        if not mapping:
            return []
        return mapping.controls_for_tier(tier)
