# app/controllers/automation.py （继续追加）
from app.core.crud import CRUDBase
from typing import List, Optional, Dict, Any
from app.models.automation import Action
from app.models.enums import ActionType
from app.schemas.automation import ActionCreate, ActionUpdate
from app.utils.common import transform_pydantic_to_list
from app.schemas.automation import NotifyAction

class ActionController(CRUDBase[Action, ActionCreate, ActionUpdate]):
    def __init__(self):
        super().__init__(model=Action)

    async def get_pending_actions_by_task(self, task_id: int) -> List[Action]:
        """获取某任务中未完成的动作"""
        return await self.model.filter(task_id=task_id, done=False).all()
    
    async def list_automation_actions(self) -> List[Dict[str, Any]]:
        """获取动作类型映射"""
        
        ActionTypeMap = [
            {"value": ActionType.CREATE_GROUP, "label": "创建群聊", "automation": True, "allowAutoExecute": False, "autoExecute": False, "enable": True},
            {"value": ActionType.VIEW_ERP_LOG, "label": "查看ERP日志", "automation": False, "allowAutoExecute": False, "autoExecute": False, "enable": True},
            {"value": ActionType.BIND_USER, "label": "绑定用户", "automation": False, "allowAutoExecute": False, "autoExecute": False, "enable": True},
            {"value": ActionType.BIND_ORDER, "label": "绑定订单", "automation": False, "allowAutoExecute": False, "autoExecute": False, "enable": True},
            {"value": ActionType.WRITE_REMARK, "label": "写ERP额外备注", "automation": True, "allowAutoExecute": True, "autoExecute": True, "enable": True},
            {"value": ActionType.SEND_WECHAT_NOTIFY, "label": "发送通知", "automation": True, "allowAutoExecute": True, "autoExecute": True, "enable": True, "schema": transform_pydantic_to_list(NotifyAction)},
            {"value": ActionType.CLEAN_GROUP, "label": "清理群聊", "automation": True, "allowAutoExecute": False, "autoExecute": True, "enable": True},
            {"value": ActionType.SET_GROUP_ADMIN, "label": "设置群管理员", "automation": True, "allowAutoExecute": False, "autoExecute": True, "enable": True},
        ]

        return [item for item in ActionTypeMap if item["automation"]]

    async def mark_action_done(
        self,
        action_id: int,
        userid: str,
        username: str,
        result: Dict[str, Any],
        notes: Optional[str] = None
    ) -> Action:
        """标记动作为已完成"""
        update_data = ActionUpdate(
            done=True,
            done_at=self.model._meta.db_fields.get("done_at").to_db_value(None, None),  # 实际用 datetime.now()
            userid=userid,
            username=username,
            result=result,
            notes=notes
        )
        # Note: 建议在 service 层处理 done_at = datetime.utcnow()
        return await self.update(action_id, update_data)

    async def create_actions_for_task(self, task_id: int, actions_def: List[Dict]) -> List[Action]:
        """为任务批量创建动作实例"""
        actions = []
        for act in actions_def:
            action_in = ActionCreate(
                task_id=task_id,
                type=act.get("type"),
                detail=act.get("detail", {}),
                done=False
            )
            action = await self.create(action_in)
            actions.append(action)
        return actions
    
    async def trigger_scenarios(self, scenario_list: List[Action], event_data: Dict[str, Any]) -> None:
        """触发场景执行"""
        for scenario in scenario_list:
            if not scenario.enabled:
                continue

            for action in scenario.actions:
                if not action.enabled:
                    continue

                if action.type == ActionType.SEND_WECHAT_NOTIFY:
                    await self.trigger_scenarios_by_action(action, event_data)


action_controller = ActionController()