

import json
import logging

# 获取日志器
logger = logging.getLogger(__name__)

data={
    "user_input_form": [
        {
            "file": {
                "variable": "files",
                "label": "files",
                "type": "file",
                "max_length": 48,
                "required": True,
                "options": [],
                "allowed_file_upload_methods": [
                    "local_file",
                    "remote_url"
                ],
                "allowed_file_types": [
                    "image",
                    "document"
                ],
                "allowed_file_extensions": []
            }
        }
    ],

}


data2={
    "user_input_form": [
        {
            "paragraph": {
                "label": "产品名称",
                "max_length": 33024,
                "options": [],
                "required": True,
                "type": "paragraph",
                "variable": "name"
            }
        },
        {
            "paragraph": {
                "label": "补充描述",
                "max_length": 33024,
                "options": [],
                "required": False,
                "type": "paragraph",
                "variable": "desc"
            }
        }
    ],
}

data3={
    "user_input_form": [
        {
            "file": {
                "allowed_file_extensions": [],
                "allowed_file_types": [
                    "document","image"
                ],
                "allowed_file_upload_methods": [
                    "local_file",
                    "remote_url"
                ],
                "label": "输入",
                "max_length": 48,
                "options": [],
                "required": True,
                "type": "file",
                "variable": "txt"
            }
        }
    ]
}

def generate_file_type_description(allowed_file_types):
    """
    根据allowed_file_types生成文件类型描述

    参数:
        allowed_file_types (list): 允许的文件类型列表

    返回:
        str: 生成的文件类型描述
    """
    # 定义各种文件类型的具体格式和中文描述
    file_type_details = {
        "document": {
            "extensions": "TXT, MD, MARKDOWN, PDF, HTML, XLSX, XLS, DOCX, CSV, EML, MSG, PPTX, PPT, XML, EPUB",
            "description": "文档文件"
        },
        "image": {
            "extensions": "JPG, JPEG, PNG, GIF, WEBP, SVG",
            "description": "图片文件"
        },
        "audio": {
            "extensions": "MP3, M4A, WAV, WEBM, AMR",
            "description": "音频文件"
        },
        "video": {
            "extensions": "MP4, MOV, MPEG, MPGA",
            "description": "视频文件"
        },
        "custom": {
            "extensions": "",
            "description": "其他文件类型"
        }
    }

    if not allowed_file_types or len(allowed_file_types) == 0:
        return "请提供有效的文件URL地址"

    # 生成描述
    descriptions = []
    all_extensions = []

    for file_type in allowed_file_types:
        if file_type in file_type_details:
            detail = file_type_details[file_type]
            if detail["extensions"]:
                descriptions.append(f"{detail['description']}({detail['extensions']})")
                all_extensions.extend(detail["extensions"].split(", "))
            else:
                descriptions.append(detail["description"])

    if descriptions:
        if len(descriptions) == 1:
            return f"请提供{descriptions[0]}的URL地址"
        else:
            return f"请提供文件URL地址，支持的文件类型：{' | '.join(descriptions)}"
    else:
        return "请提供有效的文件URL地址"


def process_user_input_form(user_input_form):
    """
    处理Dify应用的用户输入表单，转换为JSON Schema格式

    支持的控件类型:
    - text-input (object): 文本输入控件
      * label (string): 控件展示标签名
      * variable (string): 控件 ID
      * required (bool): 是否必填
      * default (string): 默认值

    - paragraph (object): 段落文本输入控件
      * label (string): 控件展示标签名
      * variable (string): 控件 ID
      * required (bool): 是否必填
      * default (string): 默认值

    - select (object): 下拉控件
      * label (string): 控件展示标签名
      * variable (string): 控件 ID
      * required (bool): 是否必填
      * default (string): 默认值
      * options (array[string]): 选项值

    - file (object): 文件上传控件 (支持复杂的文件处理逻辑)

    参数:
        user_input_form (array[object]): 用户输入表单配置

    返回:
        dict: 处理后的inputSchema字典，符合JSON Schema规范
    """
    # 初始化基础schema结构
    inputSchema = {
        "type": "object",
        "properties": {},
        "required": [],
    }

    # 如果没有用户输入表单配置，跳过处理
    if not user_input_form or len(user_input_form) == 0:
        pass
    else:
        # 遍历处理每个表单控件
        for form_item in user_input_form:
            # 检查form_item是否为None或空
            if not form_item or not isinstance(form_item, dict):
                continue

            # 获取控件类型和配置信息
            control_type = list(form_item.keys())[0]
            logger.debug(f"处理控件类型: {control_type}")
            control_config = form_item[control_type]

            # 检查control_config是否为None
            if not control_config or not isinstance(control_config, dict):
                continue

            # 提取控件基础属性
            variable = control_config.get("variable", "")
            label = control_config.get("label", "")
            required = control_config.get("required", False)
            default_value = control_config.get("default")

            # 跳过没有variable的无效控件
            if not variable:
                continue

            # 根据控件类型进行相应处理
            property_schema = None

            if control_type == "text-input":
                # 文本输入控件处理
                property_schema = {
                    "type": "string",
                    "description": label or f"文本输入字段: {variable}",
                }
                # 设置默认值
                if default_value is not None:
                    property_schema["default"] = str(default_value)

            elif control_type == "paragraph":
                # 段落文本输入控件处理
                property_schema = {
                    "type": "string",
                    "description": label or f"段落文本字段: {variable}",
                    "format": "textarea",  # 标识为多行文本输入
                }
                # 设置默认值
                if default_value is not None:
                    property_schema["default"] = str(default_value)

            elif control_type == "select":
                # 下拉控件处理
                options = control_config.get("options", [])
                property_schema = {
                    "type": "string",
                    "description": label or f"下拉选择字段: {variable}",
                }

                # 设置选项枚举值
                if options and len(options) > 0:
                    property_schema["enum"] = options

                # 设置默认值
                if default_value is not None:
                    property_schema["default"] = str(default_value)

            elif control_type in ["file", "file-list"]:
                # 文件上传控件处理 - 简化版本，仅支持remote_url
                # 获取允许的文件类型
                allowed_file_types = control_config.get("allowed_file_types", [])

                # 生成动态的URL描述
                url_description = generate_file_type_description(allowed_file_types)

                file_schema = {
                    "type": "object",
                    "description": label or f"文件上传字段: {variable}",
                    "properties": {
                        "url": {
                            "type": "string",
                            "description": url_description
                        }
                    },
                    "required": ["url"]
                }

                # 判断是单文件还是多文件
                # file-list 类型或 max_length > 1 都视为多文件
                actual_type = control_config.get("type", control_type)
                max_length = control_config.get("max_length", 1)
                is_multi_file = actual_type == "file-list" or max_length > 1
                
                if is_multi_file:
                    # 多文件上传场景
                    property_schema = {
                        "type": "array",
                        "description": label or f"多文件上传字段: {variable}",
                        "items": file_schema,
                        "maxItems": max_length,
                        "minItems": 1 if required else 0
                    }
                else:
                    # 单文件上传场景
                    property_schema = file_schema

            else:
                # 未知控件类型的默认处理
                property_schema = {
                    "type": "string",
                    "description": label or f"未知类型字段: {variable} (类型: {control_type})",
                }
                if default_value is not None:
                    property_schema["default"] = str(default_value)

            # 将处理后的属性添加到schema中
            if property_schema:
                inputSchema["properties"][variable] = property_schema

            # 处理必填字段约束
            if required:
                inputSchema["required"].append(variable)



    return inputSchema


def extract_file_fields(user_input_form):
    """
    从用户输入表单中提取所有type为file的字段信息

    参数:
        user_input_form (array[object]): 用户输入表单配置

    返回:
        list: 包含所有file类型字段信息的列表，每个元素包含：
            - variable (str): 字段变量名
            - label (str): 字段标签
            - required (bool): 是否必填
            - max_length (int): 最大文件数量
            - allowed_file_types (list): 允许的文件类型
            - allowed_file_upload_methods (list): 允许的上传方式
            - allowed_file_extensions (list): 允许的文件扩展名
            - is_list (bool): 是否为多文件类型 (file-list=True, file=False)
    """
    file_fields = []

    # 如果没有用户输入表单配置，返回空列表
    if not user_input_form or len(user_input_form) == 0:
        return file_fields

    # 遍历处理每个表单控件
    for form_item in user_input_form:
        # 检查form_item是否为None或空
        if not form_item or not isinstance(form_item, dict):
            continue

        # 获取控件类型和配置信息
        control_type = list(form_item.keys())[0]
        control_config = form_item[control_type]

        # 检查control_config是否为None
        if not control_config or not isinstance(control_config, dict):
            continue

        # 只处理type为file或file-list的字段
        if control_type in ["file", "file-list"] or control_config.get("type") in ["file", "file-list"]:
            # 判断是否为多文件类型
            # 优先使用 control_config 中的 type，其次使用 control_type
            actual_type = control_config.get("type", control_type)
            is_list = actual_type == "file-list"
            
            # 提取文件字段的详细信息
            file_field_info = {
                "variable": control_config.get("variable", ""),
                "label": control_config.get("label", ""),
                "required": control_config.get("required", False),
                "max_length": control_config.get("max_length", 1),
                "allowed_file_types": control_config.get("allowed_file_types", []),
                "allowed_file_upload_methods": control_config.get("allowed_file_upload_methods", []),
                "allowed_file_extensions": control_config.get("allowed_file_extensions", []),
                "is_list": is_list  # 新增：标识是否为多文件类型
            }

            # 只添加有效的字段（必须有variable）
            if file_field_info["variable"]:
                file_fields.append(file_field_info)

    return file_fields


if __name__ == "__main__":
    # run_main()
    result = process_user_input_form(data3["user_input_form"])
    print("开始生成 Schema...", result)

    # 保存到当前目录下的JSON文件
    output_file = "process_user_input_form_output.json"
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(result, f, ensure_ascii=False, indent=2)

    # print(f"结果已保存到: {output_file}")

    # # 测试新的extract_file_fields方法
    # print("\n=== 测试 extract_file_fields 方法 ===")

    # # 测试data（包含file字段）
    # file_fields_data = extract_file_fields(data["user_input_form"])
    # print("data中的file字段:", file_fields_data)

    # # 测试data2（不包含file字段）
    # file_fields_data2 = extract_file_fields(data2["user_input_form"])
    # print("data2中的file字段:", file_fields_data2)

    # 测试data3（包含file字段）
    # file_fields_data3 = extract_file_fields(data3["user_input_form"])
    # print("data3中的file字段:", file_fields_data3)
