"""应用 5：话术参考（骨架）。

App4 完成后自动联动触发，接收 App4 完整返回结果
作为 Prompt 中的 task_suggestion 字段。

Prompt reference 包含最近 2 套 App8 历史（附 generated_at）。

app_id = "app5_tactics"
"""

from __future__ import annotations

import json
import logging

from app.ai.bailian_client import BailianClient
from app.ai.cache_service import AICacheService
from app.ai.conversation_service import ConversationService
from app.ai.schemas import CacheTypeEnum

logger = logging.getLogger(__name__)

APP_ID = "app5_tactics"


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

    P5-A 阶段：返回占位 Prompt，标注待细化字段。
    P5-B 阶段（P6-T4）：补充 service_history、assistant_info（随 App4 同步）。

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

    Returns:
        消息列表
    """
    site_id = context["site_id"]
    assistant_id = context["assistant_id"]
    member_id = context["member_id"]
    app4_result = context.get("app4_result", {})

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

    system_content = {
        "task": "基于关系分析和任务建议，生成沟通话术参考。",
        "app_id": APP_ID,
        "task_suggestion": app4_result,
        "output_format": {
            "tactics": [
                {"scenario": "场景描述", "script": "话术内容"}
            ]
        },
        # TODO: P6-T4 细化 - service_history、assistant_info（随 App4 同步）
        "data": {
            "service_history": "待 P6-T4 补充",
            "assistant_info": "待 P6-T4 补充",
        },
        "reference": reference,
    }

    user_content = (
        f"请为助教 {assistant_id} 生成与会员 {member_id} 沟通的话术参考。"
        "返回 tactics 数组，每条包含 scenario 和 script 字段。"
    )

    return [
        {"role": "system", "content": json.dumps(system_content, ensure_ascii=False)},
        {"role": "user", "content": user_content},
    ]


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

    包含最近 2 套 App8 历史（附 generated_at）。
    缓存不存在时返回空对象 {}。
    """
    if cache_svc is None:
        return {}

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

    # 最近 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,
    bailian: BailianClient,
    cache_svc: AICacheService,
    conv_svc: ConversationService,
) -> dict:
    """执行 App5 话术参考。

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

    Returns:
        百炼返回的结构化 JSON（tactics 数组）
    """
    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 = 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.APP5_TACTICS.value,
        site_id=site_id,
        target_id=f"{assistant_id}_{member_id}",
        result_json=result,
        triggered_by=f"user:{user_id}",
    )

    logger.info(
        "App5 话术参考完成: site_id=%s assistant=%s member=%s conversation_id=%s tokens=%d",
        site_id, assistant_id, member_id, conversation_id, tokens_used,
    )

    return result
