from __future__ import annotations

from sqlalchemy.orm import Session

from app.models.financial_record import ExpenseClaim
from app.models.risk_disposition import RiskDispositionEvent
from app.models.risk_observation import RiskObservation
from app.services.expense_cases import ExpenseCaseService


class RiskDispositionLearningBridge:
    """把类型化风险处置结论桥接为同事务费用事件。"""

    def __init__(self, db: Session) -> None:
        self.db = db

    def record(
        self,
        *,
        claim: ExpenseClaim | None,
        observation: RiskObservation,
        event: RiskDispositionEvent,
        action: str,
        actor_id: str,
    ) -> None:
        # 评论、原因等自由文本刻意不进入事件，避免成为高置信学习证据。
        if claim is None or action not in {"confirm", "false_positive", "resolve"}:
            return
        ExpenseCaseService(self.db).record_claim_event(
            claim,
            event_type="audit_conclusion_recorded",
            actor_id=actor_id,
            tenant_id=observation.tenant_id,
            correlation_id=event.request_id,
            idempotency_key=f"risk-disposition:{event.id}",
            update_case_state=False,
            extra_payload={
                "audit_decision": action,
                "risk_observation_id": observation.id,
                "risk_type": str(observation.risk_type or "").strip()[:80],
                "risk_signal": str(observation.risk_signal or "").strip()[:100],
                "risk_level": str(observation.risk_level or "").strip()[:20],
            },
        )
