"""
分析报表API - 提供多维分析计划投放数据的业务接口
"""
from typing import Dict, Any, List, Optional
from loguru import logger

from mcp_framework.business.api_client import api_client

async def get_analysis_report(
    report_type: int = 15,
    start_date: str = None,
    end_date: str = None,
    dimensions: List[str] = None,
    campaign_ids: List[int] = [],
    plan_ids: List[int] = [],
    master_ids: List[int] = [],
    master_id: Optional[int] = None,
    adx_ids: List[int] = [],
    ep_ids: List[int] = [],
    slot_types: List[int] = [],
    flow_types: List[int] = [],
    customs: List[str] = [],
    sort_field: Optional[str] = None,
    sort_type: Optional[str] = None,
    is_download: bool = False,
    page: int = 1,
    page_size: int = 10,
    time_zone: int = 8,
    optimize_target_id: Optional[int] = None,
    template_ids: List[int] = [],
    bid_type: Optional[int] = None,
    rta_strategy_ids: List[int] = [],
    report_mode: Optional[int] = None,
    supplier_chain: List[int] = [],
    deal_id: Optional[str] = None,
    slot_name: Optional[str] = None,
    slot_ids: List[int] = [],
    field_rules: Optional[List[Dict[str, Any]]] = None,
    module: Optional[str] = None,
    identify: Optional[str] = None
) -> Dict[str, Any]:
    """获取多维分析报表数据
    
    Args:
        report_type: 报表类型，默认15
        start_date: 开始时间，格式为YYYY-MM-DD，必填
        end_date: 结束时间，格式为YYYY-MM-DD，必填
        dimensions: 报表维度，必填，推荐使用以下组合:
                   ["reportDate"]
                   ["reportDate", "planId"]
                   ["reportDate", "planName"]
                   ["reportDate", "masterName"] 等
        campaign_ids: 活动ID列表，必须设置，若不需要则传空列表[]
        plan_ids: 计划ID列表，必须设置，若不需要则传空列表[]
        master_ids: 账号ID列表，必须设置，若不需要则传空列表[]
        master_id: 广告主ID，单个广告主筛选
        adx_ids: ADX ID列表，必须设置，若不需要则传空列表[]
        ep_ids: EP ID列表，必须设置，若不需要则传空列表[]
        slot_types: 广告形式列表，必须设置，若不需要则传空列表[]
        flow_types: 流量类型列表，必须设置，若不需要则传空列表[]
        customs: 自定义列，必须设置，若不需要则传空列表[]
        sort_field: 排序字段
        sort_type: 排序方式
        is_download: 是否是下载
        page: 页码，默认1
        page_size: 每页记录数，默认10
        time_zone: 时区，默认8(UTC+8)
        optimize_target_id: 优化目标ID
        template_ids: 模版ID列表，必须设置，若不需要则传空列表[]
        bid_type: 出价类型
        rta_strategy_ids: RTA策略ID列表，必须设置，若不需要则传空列表[]
        report_mode: 设置类型: 0:全部；1:正常投放数据；3:ab测试数据
        supplier_chain: ssp层级列表，必须设置，若不需要则传空列表[]
        deal_id: 内部Deal id
        slot_name: 广告位名称
        slot_ids: 广告位ID列表，必须设置，若不需要则传空列表[]
        field_rules: 具体过滤指标规则
        
    Returns:
        分析报表数据响应
    """
    try:
        logger.info(f"业务层: 获取多维分析报表数据: 报表类型={report_type}, 时间范围={start_date}~{end_date}, 维度={dimensions}")
        
        # 验证必需参数
        if not start_date or not end_date or not dimensions:
            logger.error("缺少必需参数: start_date, end_date 和 dimensions")
            return {
                "success": False,
                "error": "缺少必需参数",
                "code": 400
            }
                
        # 构建请求参数
        # "module": "report_flow_list" ,  "identify": "ae_cps" 
        request_params = {
            "reportType": report_type,
            "startDate": start_date,
            "endDate": end_date,
            "dimensions": dimensions,
            "page": page,
            "pageNum": page_size,
            "timeZone": time_zone,
            "module": "report_flow_list",
            "identify": identify
        }
        
        # 确保所有列表参数不为None
        campaign_ids = campaign_ids or []
        plan_ids = plan_ids or []
        master_ids = master_ids or []
        adx_ids = adx_ids or []
        ep_ids = ep_ids or []
        slot_types = slot_types or []
        flow_types = flow_types or []
        customs = customs or []
        template_ids = template_ids or []
        rta_strategy_ids = rta_strategy_ids or []
        supplier_chain = supplier_chain or []
        slot_ids = slot_ids or []
        
        # 添加列表参数，确保传递空列表而非None
        request_params["campaignIds"] = campaign_ids
        request_params["planIds"] = plan_ids
        request_params["adxIds"] = adx_ids
        request_params["epIds"] = ep_ids
        request_params["slotTypes"] = slot_types
        request_params["flowTypes"] = flow_types
        request_params["customs"] = customs
        request_params["rtaStrategyIds"] = rta_strategy_ids
        
        if master_ids:
            request_params["masterIds"] = master_ids
        if master_id is not None:
            request_params["masterId"] = master_id

        if sort_field:
            request_params["sortField"] = sort_field
        else:
            request_params["sortField"] = dimensions[0]
        if sort_type:
            request_params["sortType"] = sort_type
        else:
            request_params["sortType"] = "desc"

        if optimize_target_id is not None:
            request_params["optimizeTargetId"] = optimize_target_id
        if template_ids:
            request_params["templateIds"] = template_ids
        if bid_type is not None:
            request_params["bidType"] = bid_type
        if report_mode is not None:
            request_params["reportMode"] = report_mode
        if supplier_chain:
            request_params["supplierChain"] = supplier_chain
        if deal_id:
            request_params["dealId"] = deal_id
        if slot_name:
            request_params["slotName"] = slot_name
        if slot_ids:
            request_params["slotIds"] = slot_ids
        if field_rules:
            request_params["fieldRules"] = field_rules
            
        # 调用API
        response = await api_client.request(
            module="report",  # 分析报表模块
            function="analysis/list",    # 列表功能
            params=request_params
        )
        
        if response.get("success"):
            # 返回标准格式响应
            return {
                "code": 0,
                "msg": "success",
                "data": response.get("data", []),
                "total": response.get("total", 0)
            }
        else:
            # 返回错误响应
            return {
                "code": response.get("code", 500),
                "msg": response.get("error", "获取分析报表失败"),
                "data": [],
                "total": 0
            }
    except Exception as e:
        logger.error(f"获取多维分析报表数据异常: {str(e)}")
        return {
            "code": 500,
            "msg": f"获取分析报表异常: {str(e)}",
            "data": [],
            "total": 0
        } 