#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Dify平台配置文件
用于管理API密钥、服务器地址等配置信息
"""

import os
from typing import Dict, Any

class DifyConfig:
    """Dify平台配置管理类"""
    
    def __init__(self):
        """初始化配置"""
        # API配置 - 请在这里填入您的实际API密钥
        self.API_KEY = os.getenv("DIFY_API_KEY", "your_dify_api_key_here")
        
        # 服务器配置 - 使用HTTPS
        self.BASE_URL = os.getenv("DIFY_BASE_URL", "https://dify.lumiidental.com/v1")
        
        # 请求配置
        self.REQUEST_TIMEOUT = 60  # 请求超时时间（秒）
        self.REQUEST_DELAY = 1.0   # 批量请求间隔时间（秒）
        self.MAX_RETRIES = 3       # 最大重试次数
        
        # API类型配置
        self.DEFAULT_API_TYPE = "agent_chat"  # 默认API类型: "chat", "completion", "workflow", "agent_chat"
        self.RESPONSE_MODE = "streaming"  # 响应模式: "blocking" 或 "streaming" (Agent模式必须用streaming)
        self.USER_ID = "callback_system"  # 默认用户ID
        
        # 输出配置
        self.OUTPUT_DIR = "data/callbacks"  # 结果输出目录
        self.LOG_LEVEL = "INFO"  # 日志级别
    
    def get_headers(self) -> Dict[str, str]:
        """获取请求头"""
        return {
            "Authorization": f"Bearer {self.API_KEY}",
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": "DifyCallbackSystem/1.0",
            "X-Requested-With": "XMLHttpRequest",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive"
        }
    
    def validate_config(self) -> bool:
        """验证配置是否完整"""
        if not self.API_KEY or self.API_KEY == "your_dify_api_key_here":
            print("错误: DIFY_API_KEY 未设置或使用默认值")
            print("请设置环境变量 DIFY_API_KEY 或在配置文件中填入实际的API密钥")
            return False
        
        if not self.BASE_URL:
            print("错误: DIFY_BASE_URL 未设置")
            return False
        
        return True
    
    def print_config(self):
        """打印当前配置信息"""
        print("当前Dify配置信息:")
        print(f"- API Key: {self.API_KEY[:10]}...{self.API_KEY[-10:] if len(self.API_KEY) > 20 else self.API_KEY}")
        print(f"- Base URL: {self.BASE_URL}")
        print(f"- Request Timeout: {self.REQUEST_TIMEOUT}s")
        print(f"- Request Delay: {self.REQUEST_DELAY}s")
        print(f"- Max Retries: {self.MAX_RETRIES}")
        print(f"- Default API Type: {self.DEFAULT_API_TYPE}")
        print(f"- Response Mode: {self.RESPONSE_MODE}")
        print(f"- User ID: {self.USER_ID}")
        print(f"- Output Directory: {self.OUTPUT_DIR}")
        print(f"- Log Level: {self.LOG_LEVEL}")

# 全局配置实例
dify_config = DifyConfig()

# API端点配置
API_ENDPOINTS = {
    "chat": "/chat-messages",
    "completion": "/completion-messages", 
    "workflow": "/workflows/run"
}

# 支持的响应模式
RESPONSE_MODES = ["blocking", "streaming"]

# 支持的API类型
API_TYPES = ["chat", "completion", "workflow", "agent_chat"]

# 患者数据字段映射（用于将现有数据格式转换为Dify输入格式）
PATIENT_DATA_MAPPING = {
    "姓名": "patient_name",
    "性别": "patient_gender", 
    "年龄": "patient_age",
    "病历号": "record_id",
    "最后一次就诊时间": "last_visit_time",
    "最后一次就诊诊所": "last_clinic",
    "最后一次就诊医生": "last_doctor",
    "上次就诊主诉": "chief_complaint",
    "上次就诊诊断": "last_diagnosis",
    "医生诊断": "doctor_diagnosis",
    "上次处置": "last_treatment",
    "上次就诊收费项": "billing_items",
    "上次就诊收费": "billing_amount",
    "下一次预约时间": "next_appointment",
    "诊所": "clinic_name",
    # 漏诊相关信息
    "漏诊项": "missed_diagnosis_items",
    "牙槽骨吸收": "alveolar_bone_resorption",
    "缺失牙": "missing_teeth",
    "恒牙萌出空间不足": "insufficient_space_for_permanent_teeth"
}

# 漏诊数据字段映射
MISSED_DIAGNOSIS_MAPPING = {
    "漏诊总次数": "missed_diagnosis_count",
    "预估治疗费用": "estimated_cost",
    "漏诊项目": "missed_items"
}

def get_dify_config():
    """获取Dify配置实例"""
    return dify_config

def validate_api_type(api_type: str) -> bool:
    """验证API类型是否支持"""
    return api_type in API_TYPES

def validate_response_mode(response_mode: str) -> bool:
    """验证响应模式是否支持"""
    return response_mode in RESPONSE_MODES

def map_patient_data(patient_data: Dict[str, Any]) -> Dict[str, Any]:
    """
    将患者数据映射为Dify输入格式
    
    Args:
        patient_data: 原始患者数据（合并结果格式）
        
    Returns:
        映射后的数据字典
    """
    mapped_data = {}
    
    # 映射所有字段（包括基础患者信息和漏诊信息）
    for chinese_field, english_field in PATIENT_DATA_MAPPING.items():
        if chinese_field in patient_data:
            value = patient_data[chinese_field]
            # 确保数值类型转换为字符串
            if isinstance(value, (int, float)):
                value = str(value)
            elif value is None:
                value = ""
            mapped_data[english_field] = str(value) if value else ""
    
    return mapped_data

if __name__ == "__main__":
    # 测试配置
    config = get_dify_config()
    config.print_config()
    
    print(f"\n配置验证结果: {'通过' if config.validate_config() else '失败'}")
    
    # 测试数据映射
    test_patient = {
        "客户": "张三",
        "年龄": 35,
        "性别": "男",
        "病历号": "TS001",
        "missed_diagnosis": {
            "漏诊总次数": 2,
            "预估治疗费用": 1500,
            "漏诊项目": [{"项目": "牙槽骨吸收", "严重程度": "轻度"}]
        }
    }
    
    print("\n数据映射测试:")
    mapped = map_patient_data(test_patient)
    for key, value in mapped.items():
        print(f"  {key}: {value}") 