from __future__ import annotations

from typing import Any

from app.core.agent_enums import AgentAssetType
from app.models.agent_asset import AgentAssetRuleFeedback
from app.schemas.agent_asset import (
    AgentAssetRiskRuleFeedbackCreate,
    AgentAssetRiskRuleFeedbackRead,
)


class AgentAssetRiskRuleFeedbackMixin:
    def create_risk_rule_feedback(
        self,
        asset_id: str,
        payload: AgentAssetRiskRuleFeedbackCreate,
        *,
        actor: str,
        request_id: str | None = None,
    ) -> AgentAssetRiskRuleFeedbackRead:
        asset = self._resolve_asset(asset_id)
        self._require_json_risk_asset(asset)
        version = self._resolve_target_version(asset, payload.version)
        feedback = AgentAssetRuleFeedback(
            asset_id=asset.id,
            version=version,
            feedback_type=str(payload.feedback_type or "").strip(),
            subject_type=str(payload.subject_type or "").strip(),
            subject_key=str(payload.subject_key or "").strip(),
            subject_label=str(payload.subject_label or "").strip(),
            actual_result_json=self._safe_json_dict(payload.actual_result),
            expected_result_json=self._safe_json_dict(payload.expected_result),
            comment=str(payload.comment or "").strip(),
            payload_json=self._safe_json_dict(payload.payload),
            created_by=str(actor or "").strip() or "system",
        )
        created = self.repository.create_rule_feedback(feedback)
        self.audit_service.log_action(
            actor=created.created_by,
            action="create_risk_rule_feedback",
            resource_type=AgentAssetType.RULE.value,
            resource_id=asset.id,
            before_json=None,
            after_json={
                "feedback_id": created.feedback_id,
                "version": created.version,
                "feedback_type": created.feedback_type,
                "subject_type": created.subject_type,
                "subject_key": created.subject_key,
            },
            request_id=request_id,
        )
        return AgentAssetRiskRuleFeedbackRead.model_validate(created)

    def list_risk_rule_feedback(
        self,
        asset_id: str,
        *,
        version: str | None = None,
        status: str | None = None,
        limit: int | None = None,
    ) -> list[AgentAssetRiskRuleFeedbackRead]:
        asset = self._resolve_asset(asset_id)
        self._require_json_risk_asset(asset)
        target_version = self._resolve_target_version(asset, version) if version else None
        return [
            AgentAssetRiskRuleFeedbackRead.model_validate(item)
            for item in self.repository.list_rule_feedback(
                asset.id,
                version=target_version,
                status=status,
                limit=limit,
            )
        ]

    @staticmethod
    def _safe_json_dict(value: Any) -> dict[str, Any]:
        return dict(value) if isinstance(value, dict) else {}
