"""应用 4：关系分析/任务建议（骨架）。

助教参与新结算或被分配召回任务时自动触发，
生成关系分析和任务建议。

Prompt reference 包含 App8 最新 + 最近 2 套历史（附 generated_at）。
缓存不存在时 reference 传空对象，标注"暂无历史线索"。

app_id = "app4_analysis"
"""

from __future__ import annotations

import asyncio
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_assistant_info,
    fetch_member_consumption_data,
    fetch_member_notes,
    fetch_service_history,
)
from app.ai.schemas import CacheTypeEnum

logger = logging.getLogger(__name__)

APP_ID = "app4_analysis"

# 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 消息列表。

    并发获取助教信息、服务历史、客户消费数据、备注，部分失败不阻断。

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

    Returns:
        消息列表
    """
    site_id = context["site_id"]
    assistant_id = context["assistant_id"]
    member_id = context["member_id"]

    # 并发获取 4 类数据，部分失败不阻断
    results = await asyncio.gather(
        fetch_assistant_info(site_id, assistant_id),
        fetch_service_history(site_id, assistant_id, member_id),
        fetch_member_consumption_data(site_id, member_id),
        fetch_member_notes(site_id, member_id),
        return_exceptions=True,
    )

    # 降级处理
    fetch_errors: list[str] = []

    if isinstance(results[0], Exception):
        logger.warning("App4 助教信息获取失败: %s", results[0])
        assistant_info = {}
        fetch_errors.append("助教信息获取失败")
    else:
        assistant_info = results[0]

    if isinstance(results[1], Exception):
        logger.warning("App4 服务历史获取失败: %s", results[1])
        service_history: list = []
        fetch_errors.append("服务历史获取失败")
    else:
        service_history = results[1]

    if isinstance(results[2], Exception):
        logger.warning("App4 消费数据获取失败: %s", results[2])
        member_data = _default_member_data()
        fetch_errors.append("消费数据获取失败")
    else:
        member_data = results[2]

    if isinstance(results[3], Exception):
        logger.warning("App4 备注获取失败: %s", results[3])
        notes: list = []
        fetch_errors.append("备注获取失败")
    else:
        notes = results[3]

    # 构建 reference：App8 最新 + 最近 2 套历史
    reference = _build_reference(site_id, member_id, cache_svc)

    system_content: dict = {
        "task": "分析助教与客户的关系，生成任务建议。",
        "app_id": APP_ID,
        "output_format": {
            "task_description": "任务描述文本",
            "action_suggestions": ["建议1", "建议2"],
            "one_line_summary": "一句话总结",
        },
        "current_time": datetime.now().strftime("%Y-%m-%d %H:%M"),
        "assistant_info": assistant_info if assistant_info else "⚠ 助教信息获取失败",
        "service_history": service_history if service_history else "暂无服务记录",
        "task_assignment_basis": {
            "consumption_records": member_data.get("consumption_records", []) or "该客户暂无消费记录",
            "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"),
        },
        "customer_data": {
            "system_data": {
                "member_nickname": member_data.get("member_nickname", ""),
            },
            "notes": notes if notes else "暂无备注",
        },
        "reference": reference,
    }

    if fetch_errors:
        system_content["_data_warnings"] = fetch_errors

    # Token 预算控制
    content_str = json.dumps(system_content, ensure_ascii=False, default=str)
    if len(content_str) > _MAX_SYSTEM_CONTENT_LEN:
        # 优先截断 service_history
        sh = system_content.get("service_history")
        if isinstance(sh, list) and len(sh) > 5:
            system_content["service_history"] = sh[:5]
            system_content["_truncated_service_history"] = f"服务记录已截断，原始共 {len(sh)} 条"
        content_str = json.dumps(system_content, ensure_ascii=False, default=str)
    if len(content_str) > _MAX_SYSTEM_CONTENT_LEN:
        records = system_content["task_assignment_basis"].get("consumption_records")
        if isinstance(records, list) and len(records) > 5:
            system_content["task_assignment_basis"]["consumption_records"] = records[:5]
            system_content["task_assignment_basis"]["_truncated"] = f"消费记录已截断，原始共 {len(records)} 条"
        content_str = json.dumps(system_content, ensure_ascii=False, default=str)
    if len(content_str) > _MAX_SYSTEM_CONTENT_LEN:
        n = system_content["customer_data"].get("notes")
        if isinstance(n, list) and len(n) > 10:
            system_content["customer_data"]["notes"] = n[:10]
            system_content["customer_data"]["_truncated_notes"] = f"备注已截断，原始共 {len(n)} 条"
        content_str = json.dumps(system_content, ensure_ascii=False, default=str)

    # 缓存不存在时在 user prompt 中标注
    no_history_hint = ""
    if not reference:
        no_history_hint = "（暂无历史线索，请基于现有信息分析）"

    user_content = (
        f"请分析助教 {assistant_id} 与会员 {member_id} 的关系，"
        f"生成任务建议。{no_history_hint}"
        "返回 task_description、action_suggestions、one_line_summary 三个字段。"
    )

    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 字段。

    包含：
    - App8 最新维客线索（如有）
    - 最近 2 套 App8 历史（附 generated_at）

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

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

    # App8 最新
    app8_latest = cache_svc.get_latest(
        CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id,
    )
    if app8_latest:
        reference["app8_latest"] = {
            "result_json": app8_latest.get("result_json"),
            "generated_at": app8_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:
    """执行 App4 关系分析。

    Args:
        context: site_id, assistant_id, member_id
        bailian: 百炼客户端
        cache_svc: 缓存服务
        conv_svc: 对话服务

    Returns:
        百炼返回的结构化 JSON（task_description, action_suggestions, one_line_summary）
    """
    site_id = context["site_id"]
    assistant_id = context["assistant_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={"assistant_id": assistant_id, "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. 写入缓存（target_id = {assistant_id}_{member_id}）
    cache_svc.write_cache(
        cache_type=CacheTypeEnum.APP4_ANALYSIS.value,
        site_id=site_id,
        target_id=f"{assistant_id}_{member_id}",
        result_json=result,
        triggered_by=f"user:{user_id}",
    )

    logger.info(
        "App4 关系分析完成: site_id=%s assistant=%s member=%s conversation_id=%s tokens=%d",
        site_id, assistant_id, member_id, conversation_id, tokens_used,
    )

    return result
