from langflow.custom import Component
from langflow.io import MessageTextInput, IntInput, Output, MultilineInput
from langflow.schema import Data, Message

from alayaflow.component.intent_classifier import execute_intent_classification
from alayaflow.component.chat_model import mk_chat_model_deepseek

class IntentClassifierComponent(Component):
    display_name = "Intent Classifier"
    description = "基于 LLM 的意图分类器，输出分类 ID 和原因。"
    icon = "Split"
    name = "IntentClassifier"

    inputs = [
        # Input(
        #     name="llm",
        #     display_name="Language Model",
        #     info="请连接一个支持 Structured Output 的模型 (如 OpenAI)。",
        #     input_types=["LanguageModel"], # 允许连接 LLM 节点
        #     required=True,
        # ),
        MessageTextInput(
            name="query",
            display_name="User Query",
            info="用户的输入文本",
            required=True,
        ),
        MultilineInput(
            name="intents_text",
            display_name="Intents List",
            info="每行输入一个意图描述。",
            value="查询订单状态\n取消订阅服务\n转人工客服",
        ),
        IntInput(
            name="fallback_index",
            display_name="Fallback Index",
            value=-1,
            advanced=True,
        ),
    ]

    outputs = [
        Output(
            name="result_data",
            display_name="Result (Data)",
            method="classify_to_data",
        ),
        Output(
            name="result_message",
            display_name="Result (Message)",
            method="classify_to_message",
        ),
    ]

    def classify_to_data(self) -> Data:
        """输出结构化数据，方便后续逻辑判断"""
        # 1. 处理输入
        query = self.query
        # 将多行文本转换为列表，去除空行
        intents = [line.strip() for line in self.intents_text.split('\n') if line.strip()]
        # model = self.llm
        model = mk_chat_model_deepseek()
        fallback = self.fallback_index

        # 2. 调用你的业务逻辑
        result = execute_intent_classification(query, intents, model, fallback)
        
        # 更新节点状态显示
        self.status = f"Classified as ID: {result.classification_id}"

        # 3. 返回 Data 对象
        return Data(data=result.model_dump())

    def classify_to_message(self) -> Message:
        """输出文本消息，方便调试查看"""
        data_output = self.classify_to_data()
        result = data_output.data
        
        text_output = (
            f"分类结果 ID: {result.get('classification_id', 'N/A')}\n"
            f"原因: {result.get('reason', 'N/A')}"
        )
        return Message(text=text_output)
