"""Deterministic (offline) explanations from controls YAML.

Available at all tiers. No API key required.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from complyform.core.explainer.models import Explanation
from complyform.core.profiles.control_loader import get_control

if TYPE_CHECKING:
    from complyform.core.assessor.control_matcher import Finding

SEVERITY_DESCRIPTIONS: dict[str, str] = {
    "CRITICAL": (
        "Immediate action required — this control failure creates direct exposure."
    ),
    "HIGH": ("Address within current sprint — significant compliance risk."),
    "MEDIUM": ("Plan remediation — moderate risk, typically configuration hardening."),
    "LOW": "Address when convenient — minimal direct risk.",
}


def explain_finding(finding: Finding) -> Explanation:
    """Build a deterministic explanation from control metadata + finding."""
    control = get_control(finding.framework, finding.control_id)

    if control is not None:
        title = control.title
        description = control.description or title
        family = control.family
    else:
        title = finding.finding or f"Control {finding.control_id}"
        description = title
        family = ""

    why_it_matters = _build_why_it_matters(
        description=description,
        family=family,
    )

    severity_rationale = _build_severity_rationale(finding.severity)

    remediation_hint = _build_remediation_hint(finding=finding)

    summary = _build_summary(
        title=title,
        status=finding.status,
        resource_address=finding.resource_address,
    )

    return Explanation(
        control_id=finding.control_id,
        framework=finding.framework,
        title=title,
        severity=finding.severity,
        status=finding.status,
        summary=summary,
        why_it_matters=why_it_matters,
        severity_rationale=severity_rationale,
        remediation_hint=remediation_hint,
        resource_address=finding.resource_address,
        ai_generated=False,
        model=None,
        cached=False,
    )


def _build_summary(*, title: str, status: str, resource_address: str) -> str:
    status_label = {
        "PASS": "passes",
        "FAIL": "fails",
        "MANUAL_REVIEW": "requires manual review for",
        "NOT_ASSESSED": "was not assessed for",
    }.get(status, "was evaluated for")
    return f"Resource '{resource_address}' {status_label} control: {title}."


def _build_why_it_matters(*, description: str, family: str) -> str:
    parts = [description.rstrip(".") + "."]
    if family:
        parts.append(f"Control family: {family}.")
    return " ".join(parts)


def _build_severity_rationale(severity: str) -> str:
    desc = SEVERITY_DESCRIPTIONS.get(severity, "")
    return f"Severity: {severity}. {desc}".rstrip()


def _build_remediation_hint(*, finding: Finding) -> str:
    if finding.status == "PASS":
        return "No action needed — this control is already satisfied."
    if finding.remediation:
        return finding.remediation
    return (
        "Review the control requirements and update your infrastructure configuration."
    )
