"""应用 3：客户数据维客线索分析（骨架）。

客户新增消费时自动触发，通过 AI 分析客户数据提取维客线索。
线索 category 限定 3 个枚举值：客户基础、消费习惯、玩法偏好。
线索提供者统一标记为"系统"。

使用 items_sum 口径（= table_charge_money + goods_money
+ assistant_pd_money + assistant_cx_money + electricity_money），
禁止使用 consume_money。

app_id = "app3_clue"
"""

from __future__ import annotations

import json
import logging
from datetime import datetime

from app.ai.dashscope_client import DashScopeClient
from app.ai.cache_service import AICacheService
from app.ai.conversation_service import ConversationService
from app.ai.data_fetchers import fetch_member_consumption_data
from app.ai.schemas import CacheTypeEnum

logger = logging.getLogger(__name__)

APP_ID = "app3_clue"

# system message content 上限
_MAX_SYSTEM_CONTENT_LEN = 8000


def _default_member_data() -> dict:
    """数据获取失败时的默认空值。"""
    return {
        "member_nickname": "",
        "consumption_records": [],
        "member_cards": [],
        "card_balance_total": 0,
        "stored_value_balance_total": 0,
        "expected_visit_date": None,
        "days_since_last_visit": None,
    }


async def build_prompt(
    context: dict,
    cache_svc: AICacheService | None = None,
) -> list[dict]:
    """构建 Prompt 消息列表。

    从 data_fetchers 获取真实消费数据，失败时降级为空值。

    Args:
        context: 包含 site_id, member_id, nickname 等
        cache_svc: 缓存服务，用于获取 reference 历史数据

    Returns:
        消息列表 [{"role": "system", "content": ...}, {"role": "user", ...}]
    """
    site_id = context["site_id"]
    member_id = context["member_id"]

    # 获取消费数据（失败时降级）
    data_fetch_failed = False
    try:
        member_data = await fetch_member_consumption_data(site_id, member_id)
    except Exception:
        logger.warning("App3 消费数据获取失败，使用默认空值: site_id=%s member_id=%s", site_id, member_id, exc_info=True)
        member_data = _default_member_data()
        data_fetch_failed = True

    # 构建 reference：App6 线索 + 最近 2 套 App8 历史（附 generated_at）
    reference = _build_reference(site_id, member_id, cache_svc)

    member_nickname = member_data.get("member_nickname", "")
    consumption_records = member_data.get("consumption_records", [])

    # 空数据标注
    if not consumption_records:
        if data_fetch_failed:
            consumption_records = "⚠ 消费数据获取失败，该客户暂无消费记录可供分析"
        else:
            consumption_records = "该客户暂无消费记录"

    system_content = {
        "task": "分析客户消费数据，提取维客线索。",
        "app_id": APP_ID,
        "rules": {
            "category_enum": ["客户基础", "消费习惯", "玩法偏好"],
            "providers": "系统",
            "amount_caliber": "items_sum = table_charge_money + goods_money + assistant_pd_money + assistant_cx_money + electricity_money",
            "禁止使用": "consume_money",
        },
        "output_format": {
            "clues": [
                {
                    "category": "枚举值（客户基础/消费习惯/玩法偏好）",
                    "summary": "一句话摘要",
                    "detail": "详细说明",
                    "emoji": "表情符号",
                }
            ]
        },
        "current_time": datetime.now().strftime("%Y-%m-%d %H:%M"),
        "member_nickname": member_nickname,
        "main_data": {
            "consumption_records": consumption_records,
            "member_cards": member_data.get("member_cards", []),
            "card_balance_total": member_data.get("card_balance_total", 0),
            "stored_value_balance_total": member_data.get("stored_value_balance_total", 0),
            "expected_visit_date": member_data.get("expected_visit_date"),
            "days_since_last_visit": member_data.get("days_since_last_visit"),
        },
        "reference": reference,
    }

    # Token 预算控制：截断 consumption_records
    content_str = json.dumps(system_content, ensure_ascii=False, default=str)
    if len(content_str) > _MAX_SYSTEM_CONTENT_LEN:
        records = system_content["main_data"].get("consumption_records")
        if isinstance(records, list) and len(records) > 5:
            system_content["main_data"]["consumption_records"] = records[:5]
            system_content["main_data"]["_truncated"] = f"消费记录已截断，原始共 {len(records)} 条"
        content_str = json.dumps(system_content, ensure_ascii=False, default=str)

    user_content = (
        f"请分析会员 {member_id} 的消费数据，提取维客线索。"
        "每条线索包含 category、summary、detail、emoji 四个字段。"
        "category 必须是：客户基础、消费习惯、玩法偏好 之一。"
    )

    return [
        {"role": "system", "content": content_str},
        {"role": "user", "content": user_content},
    ]


def _build_reference(
    site_id: int,
    member_id: int,
    cache_svc: AICacheService | None,
) -> dict:
    """构建 Prompt reference 字段。

    包含：
    - App6 备注分析线索（最新一条，如有）
    - 最近 2 套 App8 维客线索整理历史（附 generated_at）

    缓存不存在时返回空对象 {}。
    """
    if cache_svc is None:
        return {}

    reference: dict = {}
    target_id = str(member_id)

    # App6 备注分析线索
    app6_latest = cache_svc.get_latest(
        CacheTypeEnum.APP6_NOTE_ANALYSIS.value, site_id, target_id,
    )
    if app6_latest:
        reference["app6_note_clues"] = {
            "result_json": app6_latest.get("result_json"),
            "generated_at": app6_latest.get("created_at"),
        }

    # 最近 2 套 App8 历史
    app8_history = cache_svc.get_history(
        CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, limit=2,
    )
    if app8_history:
        reference["app8_history"] = [
            {
                "result_json": h.get("result_json"),
                "generated_at": h.get("created_at"),
            }
            for h in app8_history
        ]

    return reference


async def run(
    context: dict,
    client: DashScopeClient,
    cache_svc: AICacheService,
    conv_svc: ConversationService,
) -> dict:
    """执行 App3 客户数据维客线索分析。

    流程：
    1. build_prompt 构建 Prompt
    2. bailian.chat_json 调用百炼
    3. 写入 conversation + messages
    4. 写入 ai_cache
    5. 返回结果

    Args:
        context: site_id, member_id, user_id(默认'system'), nickname(默认'')
        bailian: 百炼客户端
        cache_svc: 缓存服务
        conv_svc: 对话服务

    Returns:
        百炼返回的结构化 JSON（clues 数组）
    """
    site_id = context["site_id"]
    member_id = context["member_id"]
    user_id = context.get("user_id", "system")
    nickname = context.get("nickname", "")

    # 1. 构建 Prompt
    messages = await build_prompt(context, cache_svc)

    # 2. 创建对话记录
    conversation_id = conv_svc.create_conversation(
        user_id=user_id,
        nickname=nickname,
        app_id=APP_ID,
        site_id=site_id,
        source_context={"member_id": member_id},
    )

    # 写入 system + user 消息
    conv_svc.add_message(
        conversation_id=conversation_id,
        role="system",
        content=messages[0]["content"],
    )
    conv_svc.add_message(
        conversation_id=conversation_id,
        role="user",
        content=messages[1]["content"],
    )

    # 3. 调用百炼 API
    result, tokens_used = await bailian.chat_json(messages)

    # 4. 写入 assistant 消息
    conv_svc.add_message(
        conversation_id=conversation_id,
        role="assistant",
        content=json.dumps(result, ensure_ascii=False),
        tokens_used=tokens_used,
    )

    # 5. 写入缓存
    cache_svc.write_cache(
        cache_type=CacheTypeEnum.APP3_CLUE.value,
        site_id=site_id,
        target_id=str(member_id),
        result_json=result,
        triggered_by=f"user:{user_id}",
    )

    logger.info(
        "App3 线索分析完成: site_id=%s member_id=%s conversation_id=%s tokens=%d",
        site_id, member_id, conversation_id, tokens_used,
    )

    return result
