"""Counterfactual recommendations for reducing financial risk scores."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any


@dataclass(slots=True)
class CounterfactualRiskAction:
    action_key: str
    title: str
    detail: str
    related_feature: str
    expected_score_delta: int

    def as_dict(self) -> dict[str, Any]:
        return {
            "action_key": self.action_key,
            "title": self.title,
            "detail": self.detail,
            "related_feature": self.related_feature,
            "expected_score_delta": self.expected_score_delta,
        }


class CounterfactualRiskAdvisor:
    def advise(self, observation: dict[str, Any]) -> list[CounterfactualRiskAction]:
        scores = dict(
            observation.get("contribution_scores")
            or observation.get("decision_trace", {}).get("input_scores")
            or {}
        )
        evidence_codes = {
            str(item.get("code") or "")
            for item in observation.get("evidence", [])
            if isinstance(item, dict)
        }
        trace = observation.get("decision_trace") or {}
        actions: list[CounterfactualRiskAction] = []

        if int(scores.get("S_rule") or 0) >= 70:
            actions.append(
                CounterfactualRiskAction(
                    action_key="complete_preapproval_or_required_attachment",
                    title="Complete required approval evidence",
                    detail="补齐事前申请、审批记录或制度要求的附件，可降低规则命中风险。",
                    related_feature="S_rule",
                    expected_score_delta=-20,
                )
            )
        if int(scores.get("S_anomaly") or 0) >= 70:
            actions.append(
                CounterfactualRiskAction(
                    action_key="align_amount_with_peer_baseline",
                    title="Align amount with peer baseline",
                    detail="补充高金额原因或拆出不属于本次报销的费用，可降低基线偏离风险。",
                    related_feature="S_anomaly",
                    expected_score_delta=-18,
                )
            )
        if int(scores.get("S_graph") or 0) >= 70 or "duplicate_invoice_graph" in evidence_codes:
            actions.append(
                CounterfactualRiskAction(
                    action_key="replace_duplicate_or_conflicting_invoice",
                    title="Replace conflicting invoice",
                    detail="替换重复票据、修正票据归属或说明跨单据复用原因，可降低图谱异常风险。",
                    related_feature="S_graph",
                    expected_score_delta=-25,
                )
            )
        if trace.get("data_quality_gate") not in {"", "passed", None}:
            actions.append(
                CounterfactualRiskAction(
                    action_key="supplement_missing_risk_data",
                    title="Supplement missing risk data",
                    detail="补齐员工、金额、费用类型、票据明细等关键字段后再进入强风控判断。",
                    related_feature="data_quality",
                    expected_score_delta=-10,
                )
            )
        return actions
