#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8

import random
from typing import Dict, List

from openai import OpenAI
from datetime import datetime
import re
from pqai_agent import chat_service
from pqai_agent import configs
from pqai_agent import prompt_templates
from pqai_agent.dialogue_manager import DialogueManager
from pqai_agent.logging_service import logger
from pqai_agent.message import MessageType


class ResponseTypeDetector:
    @staticmethod
    def compose_dialogue(dialogue):
        role_map = {'user': '用户', 'assistant': '客服'}
        messages = []
        for msg in dialogue:
            if not msg['content']:
                continue
            if msg['role'] not in role_map:
                continue
            msg_type = msg.get('type', MessageType.TEXT)
            fmt_time = datetime.fromtimestamp(msg['timestamp'] / 1000).strftime('%Y-%m-%d %H:%M:%S')
            messages.append('[{}][{}][{}] {}'.format(role_map[msg['role']], fmt_time, msg_type.description, msg['content']))
        return '\n'.join(messages)

    def __init__(self):
        self.llm_client = OpenAI(
            api_key=chat_service.VOLCENGINE_API_TOKEN,
            base_url=chat_service.VOLCENGINE_BASE_URL
        )
        self.model_name = chat_service.VOLCENGINE_MODEL_DOUBAO_PRO_1_5

    def detect_type(self, dialogue_history: List[Dict], next_message: Dict, enable_random=False):
        if configs.get().get('debug_flags', {}).get('disable_llm_api_call', False):
            return MessageType.TEXT
        composed_dialogue = self.compose_dialogue(dialogue_history)
        fmt_next_message = DialogueManager.format_dialogue_content(next_message)
        prompt = prompt_templates.RESPONSE_TYPE_DETECT_PROMPT.format(
            dialogue_history=composed_dialogue,
            message=fmt_next_message
        )
        # logger.debug(prompt)
        messages = [
            {'role': 'system', 'content': '你是一个专业的智能助手'},
            {'role': 'user', 'content': prompt}
        ]
        response = self.llm_client.chat.completions.create(messages=messages, model=self.model_name,
                                                           temperature=0.2, max_tokens=128)
        response = response.choices[0].message.content.strip()
        if response == '语音':
            return MessageType.VOICE
        if enable_random:
            next_message_content = next_message['content']
            suitable_for_voice = self.if_message_suitable_for_voice(next_message_content)
            logger.debug(f"voice suitable[{suitable_for_voice}], message: {next_message_content}")
            if suitable_for_voice:
                if random.random() < 0.6:
                    logger.info(f"enable voice response randomly for message: {next_message_content}")
                    return MessageType.VOICE
        return MessageType.TEXT

    @staticmethod
    def is_chinese_only(text):
        # 匹配中文字符和中文标点
        pattern = re.compile(r'^[\u4e00-\u9fa5，。！？、；："\'‘’“”（）【】《》…—~.,!?;:\[\]\(\)\{\}\<\>]+$')
        return bool(pattern.fullmatch(text))

    @staticmethod
    def if_message_suitable_for_voice(message):
        if not message:
            return False
        # 使用语音的文字不适合过长
        if len(message) > 50:
            return False
        # 只有纯文字的消息适合使用语音
        if not ResponseTypeDetector.is_chinese_only(message):
            return False
        return True