import { z } from 'zod';
import type { JSONSchema } from '../nodes/types';

/**
 * 将 JSON Schema 转换为 Zod Schema
 * @param jsonSchema JSON Schema 定义
 * @returns Zod Schema
 */
export const convertJsonSchemaToZod = (jsonSchema: JSONSchema): z.ZodObject<any> => {
    const shape: Record<string, z.ZodTypeAny> = {};

    if (!jsonSchema.properties || typeof jsonSchema.properties !== 'object') {
        return z.object({});
    }

    Object.entries(jsonSchema.properties).forEach(([key, prop]: [string, any]) => {
        let fieldSchema: z.ZodTypeAny;
        const isRequired = Array.isArray(jsonSchema.required) && jsonSchema.required.includes(key);

        // 如果有枚举，直接使用枚举（枚举会覆盖其他类型）
        if (prop.enum && Array.isArray(prop.enum)) {
            const enumValues = prop.enum.map((v: any) => (typeof v === 'object' ? v.value : v));
            fieldSchema = z.enum(enumValues as [string, ...string[]]);
            
            // 处理默认值
            if (prop.default !== undefined) {
                fieldSchema = fieldSchema.default(prop.default);
            }
            
            // 处理必填/可选
            if (!isRequired) {
                fieldSchema = fieldSchema.optional();
            }
        } else {
            // 根据类型创建 Zod Schema
            switch (prop.type) {
                case 'string': {
                    let stringSchema = z.string();
                    
                    // 必填字段需要非空验证
                    if (isRequired) {
                        stringSchema = stringSchema.min(1, `${prop.title || key}不能为空`);
                    }
                    
                    if (prop.format === 'email') {
                        stringSchema = stringSchema.email(prop.title ? `${prop.title}格式不正确` : '邮箱格式不正确');
                    } else if (prop.format === 'url') {
                        stringSchema = stringSchema.url(prop.title ? `${prop.title}格式不正确` : 'URL格式不正确');
                    }
                    if (prop.minLength) {
                        stringSchema = stringSchema.min(prop.minLength, `${prop.title || key}至少需要${prop.minLength}个字符`);
                    }
                    if (prop.maxLength) {
                        stringSchema = stringSchema.max(prop.maxLength, `${prop.title || key}最多${prop.maxLength}个字符`);
                    }
                    if (prop.pattern) {
                        stringSchema = stringSchema.regex(new RegExp(prop.pattern), `${prop.title || key}格式不正确`);
                    }
                    
                    fieldSchema = stringSchema;
                    break;
                }

                case 'number':
                case 'integer':
                    fieldSchema = prop.type === 'integer' ? z.number().int() : z.number();
                    if (prop.minimum !== undefined) {
                        fieldSchema = (fieldSchema as z.ZodNumber).min(prop.minimum, `${prop.title || key}不能小于${prop.minimum}`);
                    }
                    if (prop.maximum !== undefined) {
                        fieldSchema = (fieldSchema as z.ZodNumber).max(prop.maximum, `${prop.title || key}不能大于${prop.maximum}`);
                    }
                    break;

                case 'boolean':
                    fieldSchema = z.boolean();
                    break;

                case 'array':
                    fieldSchema = z.array(z.any());
                    if (prop.minItems !== undefined) {
                        fieldSchema = (fieldSchema as z.ZodArray<any>).min(prop.minItems, `${prop.title || key}至少需要${prop.minItems}项`);
                    }
                    if (prop.maxItems !== undefined) {
                        fieldSchema = (fieldSchema as z.ZodArray<any>).max(prop.maxItems, `${prop.title || key}最多${prop.maxItems}项`);
                    }
                    break;

                case 'object':
                    fieldSchema = z.record(z.any());
                    break;

                default:
                    fieldSchema = z.any();
            }

            // 处理默认值
            if (prop.default !== undefined) {
                fieldSchema = fieldSchema.default(prop.default);
            }

            // 处理可选字段
            if (!isRequired) {
                fieldSchema = fieldSchema.optional();
            }
        }

        shape[key] = fieldSchema;
    });

    return z.object(shape);
};

/**
 * 从 JSON Schema 中提取需要动态加载的字段
 * @param jsonSchema JSON Schema 定义
 * @returns 需要加载的数据源类型列表
 */
export const extractDataSourceTypes = (jsonSchema: JSONSchema): string[] => {
    const types: string[] = [];

    if (!jsonSchema.properties || typeof jsonSchema.properties !== 'object') {
        return types;
    }

    Object.values(jsonSchema.properties).forEach((prop: any) => {
        if (prop['x-dataSource']) {
            types.push(prop['x-dataSource']);
        }
    });

    return types;
};

