# app/api/v1/automation.py

import logging
from typing import Dict, Any
from app.http_base import unified_resp
from fastapi import APIRouter, Query, Depends
from tortoise.expressions import Q
from app.controllers.automation.scenario import automation_scenario_controller
from app.controllers.automation.task import task_controller
from app.controllers.automation.action import action_controller
from app.schemas.automation import (
    ScenarioCreate,
    ScenarioUpdate,
    ScenarioCopy,
    TaskUpdate,
    ActionUpdate,
)
from app.schemas.base import Success, SuccessExtra, Fail
from app.schemas.apis import Paginate
from ..weixin.base import get_weixin_user

logger = logging.getLogger(__name__)

router = APIRouter()


# ============================
# Scenario 路由
# ============================

@router.get("/scenario/list", summary="查看场景列表")
@unified_resp
async def list_automation_scenario(
    pagination: Paginate = Depends(),
    title: str = Query("", description="场景标题，用于搜索"),
    is_global: bool = Query(None, description="是否全局场景"),
    enabled: bool = Query(None, description="是否启用"),
    owner_user_id: str = Query("", description="归属用户ID（非全局时）"),
):
    q = Q(visible=True)
    if title:
        q &= Q(title__contains=title)
    if is_global is not None:
        q &= Q(is_global=is_global)
    if enabled is not None:
        q &= Q(enabled=enabled)
    if owner_user_id:
        q &= Q(owner_user_id=owner_user_id)

    total, scenario_objs = await automation_scenario_controller.list(
        page=pagination.page, page_size=pagination.page_size, search=q, order=["-created_at"]
    )
    data = [await obj.to_dict() for obj in scenario_objs]
    return {"count": total, "lists": data, "page": pagination.page, "page_size": pagination.page_size}


@router.get("/scenario/event_and_action", summary="查看场景事件和动作")
@unified_resp
async def list_event_and_action():
    actions = await action_controller.list_automation_actions()
    events = await automation_scenario_controller.list_automation_events()
    return {"events": events, "actions": actions}


@router.get("/scenario/get/{id}", summary="查看场景详情")
@unified_resp
async def get_automation_scenario(id: int):
    obj = await automation_scenario_controller.get(id=id)
    return await obj.to_dict()


@router.post("/scenario/create", summary="创建场景")
@unified_resp
async def create_automation_scenario(
    scenario_in: ScenarioCreate,
    weixin_user: dict = Depends(get_weixin_user)
):
    obj = await automation_scenario_controller.new_scenario(scenario_in, weixin_user.userid)
    return await obj.to_dict()


@router.post("/scenario/copy", summary="复制场景")
@unified_resp
async def copy_automation_scenario(
    scenario_in: ScenarioCopy,
):
    def handler(obj_dict: Dict[str, Any]) -> Dict[str, Any]:
        obj_dict["title"] = f"复制：{obj_dict['title']}"
        obj_dict["enabled"] = False
        return obj_dict
    
    obj = await automation_scenario_controller.copy(id=scenario_in.id, handler=handler)
    return await obj.to_dict()


@router.post("/scenario/update", summary="更新场景")
@unified_resp
async def update_automation_scenario(
    scenario_in: ScenarioUpdate,
    weixin_user: dict = Depends(get_weixin_user)
):
    obj = await automation_scenario_controller.update_scenario(scenario_in=scenario_in, user_id=weixin_user.userid)
    return await obj.to_dict()


@router.delete("/scenario/delete", summary="删除场景")
@unified_resp
async def delete_automation_scenario(
    id: int = Query(..., description="场景ID"),
):
    await automation_scenario_controller.remove_scenario(scenario_id=id)
    return Success(msg="Deleted Successfully")


# ============================
# Task 路由
# ============================

@router.get("/task/list", summary="查看待办列表")
@unified_resp
async def list_task(
    pagination: Paginate = Depends(),
    assignee_user_id: str = Query("", description="指派人用户ID"),
    status: str = Query("", description="任务状态"),
    related_customer_id: str = Query("", description="关联客户ID"),
):
    q = Q()
    if assignee_user_id:
        q &= Q(assignee_user_id=assignee_user_id)
    if status:
        q &= Q(status=status)
    if related_customer_id:
        q &= Q(related_customer_id=related_customer_id)

    total, task_objs = await task_controller.list(
        page=pagination.page, page_size=pagination.page_size, search=q
        # , order=["-created_at"]
    )
    data = [await obj.to_dict() for obj in task_objs]
    return {"count": total, "lists": data, "page": pagination.page, "page_size": pagination.page_size}


@router.get("/task/get", summary="查看待办详情")
@unified_resp
async def get_task(
    id: int = Query(..., description="待办ID"),
):
    obj = await task_controller.get(id=id)
    return await obj.to_dict()


@router.post("/task/update", summary="更新待办")
@unified_resp
async def update_task(
    task_in: TaskUpdate,
):
    obj = await task_controller.update(id=task_in.id, obj_in=task_in)
    return await obj.to_dict()


# ============================
# Action 路由
# ============================

@router.get("/action/list", summary="查看动作列表（按任务）")
@unified_resp
async def list_action(
    task_id: int = Query(..., description="所属任务ID"),
):
    actions = await action_controller.model.filter(task_id=task_id).all()
    data = [await act.to_dict() for act in actions]
    return data


# @router.get("/action/type", summary="查看动作类型列表（按任务）")
# @unified_resp
# async def list_action_type():
#     actions = await action_controller.list_automation_actions()
#     return actions


@router.post("/action/update", summary="更新动作（如标记完成）")
@unified_resp
async def update_action(
    action_in: ActionUpdate,
):
    obj = await action_controller.update(id=action_in.id, obj_in=action_in)
    return await obj.to_dict()