# app/controllers/automation.py （继续追加）
from app.core.crud import CRUDBase
from typing import List, Optional, Dict, Any, Tuple

from tortoise.expressions import Q
from app.models.automation import Task, Scenario, ScenarioScope
from app.schemas.automation import TaskCreate, TaskUpdate
from datetime import datetime, timedelta

class TaskController(CRUDBase[Task, TaskCreate, TaskUpdate]):
    def __init__(self):
        super().__init__(model=Task)

    async def get_user_tasks(
        self,
        user_id: str,
        status: Optional[str] = None,
        page: int = 1,
        page_size: int = 20
    ) -> Tuple[int, List[Task]]:
        """分页获取某用户的待办（支持按状态过滤）"""
        query = Q(assignee_user_id=user_id)
        if status:
            query &= Q(status=status)
        return await self.list(page=page, page_size=page_size, search=query, order=["-created_at"])

    async def get_tasks_by_customer(self, customer_id: str) -> List[Task]:
        """获取与某客户相关的所有待办（用于侧边栏上下文）"""
        return await self.model.filter(related_customer_id=customer_id).order_by("-created_at").all()

    async def create_from_scenario(
        self,
        scenario: Scenario,
        event_data: Optional[Dict[str, Any]] = None,
        assignee_user_id: Optional[str] = None,
        assignee_username: Optional[str] = None,
        reason: Optional[str] = None,
    ) -> Task:
        """根据场景模板创建待办任务"""
        # 计算截止时间（示例：场景中定义的 due_days 天后）
        due_at = scenario.due_days and (datetime.now() + timedelta(days=scenario.due_days)) or None

        owner_user_id = None
        if scenario.scope == ScenarioScope.ALL:
            owner_user_id = ScenarioScope.ALL
        elif scenario.scope == ScenarioScope.PERSONAL:
            owner_user_id = scenario.owner_user_id

        task_in = TaskCreate(
            title=scenario.title,
            reason=reason,
            notes=scenario.notes,
            event_data=event_data or {},
            source_scenario=scenario,
            source_scenario_id=scenario.id,
            owner_user_id=owner_user_id,
            assignee_user_id=assignee_user_id,
            assignee_username=assignee_username,
            due_at=due_at,
            status="pending",
            auto_closeable=True,
        )
        return await self.create(task_in)

    async def auto_close_by_event(self, event_type: str, payload: Dict[str, Any]) -> List[Task]:
        """
        根据事件自动关闭匹配的待办（用于自动消除）
        例如：当 group_id 匹配且动作含 create_group 时，关闭待办
        """
        # 示例逻辑：后续可扩展为规则引擎
        closed_tasks = []
        # 这里可遍历 pending 任务，检查 content 中的动作是否已被事件满足
        # 为简化，此处留作扩展点
        return closed_tasks


task_controller = TaskController()