import * as vscode from 'vscode';

// API函数信息接口
export interface ApiFunction {
    name: string;
    description: string;
    params: ApiParameter[];
    returns?: ApiReturn;
    example?: string;
}

// API参数信息接口
export interface ApiParameter {
    name: string;
    type: string;
    description: string;
    optional?: boolean;
    defaultValue?: string;
}

// API返回值信息接口
export interface ApiReturn {
    type: string;
    description: string;
}

// API类信息接口
export interface ApiClass {
    name: string;
    description: string;
    methods: ApiFunction[];
    properties: ApiProperty[];
}

// API属性信息接口
export interface ApiProperty {
    name: string;
    type: string;
    description: string;
}

// API常量信息接口
export interface ApiConstant {
    name: string;
    value: string;
    description: string;
    category: string;
}

// API文档解析器类
export class ApiParser {
    private static instance: ApiParser;
    private functions: ApiFunction[] = [];
    private classes: ApiClass[] = [];
    private constants: ApiConstant[] = [];

    private constructor() {
        this.initializeApiDocumentation();
    }

    // 获取单例实例
    public static getInstance(): ApiParser {
        if (!ApiParser.instance) {
            ApiParser.instance = new ApiParser();
        }
        return ApiParser.instance;
    }

    // 初始化API文档
    private initializeApiDocumentation(): void {
        // 初始化内置函数
        this.functions = [
            {
                name: 'print',
                description: '打印消息到控制台',
                params: [
                    {
                        name: 'message',
                        type: 'string',
                        description: '要打印的消息'
                    }
                ],
                returns: {
                    type: 'void',
                    description: '无返回值'
                }
            },
            {
                name: 'len',
                description: '返回字符串、数组或表的长度',
                params: [
                    {
                        name: 'obj',
                        type: 'string|table|array',
                        description: '要计算长度的对象'
                    }
                ],
                returns: {
                    type: 'integer',
                    description: '对象的长度'
                }
            },
            {
                name: 'type',
                description: '返回对象的类型',
                params: [
                    {
                        name: 'obj',
                        type: 'any',
                        description: '要检查类型的对象'
                    }
                ],
                returns: {
                    type: 'string',
                    description: '对象的类型字符串'
                }
            },
            {
                name: 'clone',
                description: '创建对象的浅拷贝',
                params: [
                    {
                        name: 'obj',
                        type: 'any',
                        description: '要克隆的对象'
                    }
                ],
                returns: {
                    type: 'any',
                    description: '克隆的对象'
                }
            },
            {
                name: 'tostring',
                description: '将对象转换为字符串',
                params: [
                    {
                        name: 'obj',
                        type: 'any',
                        description: '要转换的对象'
                    }
                ],
                returns: {
                    type: 'string',
                    description: '转换后的字符串'
                }
            },
            {
                name: 'tointeger',
                description: '将对象转换为整数',
                params: [
                    {
                        name: 'obj',
                        type: 'any',
                        description: '要转换的对象'
                    }
                ],
                returns: {
                    type: 'integer',
                    description: '转换后的整数'
                }
            },
            {
                name: 'tofloat',
                description: '将对象转换为浮点数',
                params: [
                    {
                        name: 'obj',
                        type: 'any',
                        description: '要转换的对象'
                    }
                ],
                returns: {
                    type: 'float',
                    description: '转换后的浮点数'
                }
            }
        ];

        // 初始化内置类
        this.classes = [
            {
                name: 'String',
                description: '字符串类，提供字符串操作方法',
                methods: [
                    {
                        name: 'len',
                        description: '返回字符串长度',
                        params: [],
                        returns: {
                            type: 'integer',
                            description: '字符串的长度'
                        }
                    },
                    {
                        name: 'slice',
                        description: '返回字符串的子串',
                        params: [
                            {
                                name: 'start',
                                type: 'integer',
                                description: '起始位置'
                            },
                            {
                                name: 'end',
                                type: 'integer',
                                description: '结束位置（可选）',
                                optional: true
                            }
                        ],
                        returns: {
                            type: 'string',
                            description: '子串'
                        }
                    },
                    {
                        name: 'find',
                        description: '查找子串在字符串中的位置',
                        params: [
                            {
                                name: 'substr',
                                type: 'string',
                                description: '要查找的子串'
                            }
                        ],
                        returns: {
                            type: 'integer',
                            description: '子串的位置，未找到返回-1'
                        }
                    }
                ],
                properties: [
                    {
                        name: 'length',
                        type: 'integer',
                        description: '字符串的长度'
                    }
                ]
            },
            {
                name: 'Array',
                description: '数组类，提供数组操作方法',
                methods: [
                    {
                        name: 'len',
                        description: '返回数组长度',
                        params: [],
                        returns: {
                            type: 'integer',
                            description: '数组的长度'
                        }
                    },
                    {
                        name: 'append',
                        description: '向数组末尾添加元素',
                        params: [
                            {
                                name: 'value',
                                type: 'any',
                                description: '要添加的元素'
                            }
                        ],
                        returns: {
                            type: 'void',
                            description: '无返回值'
                        }
                    },
                    {
                        name: 'pop',
                        description: '移除并返回数组最后一个元素',
                        params: [],
                        returns: {
                            type: 'any',
                            description: '被移除的元素'
                        }
                    }
                ],
                properties: [
                    {
                        name: 'length',
                        type: 'integer',
                        description: '数组的长度'
                    }
                ]
            },
            {
                name: 'Table',
                description: '表类，提供表操作方法',
                methods: [
                    {
                        name: 'len',
                        description: '返回表中键值对的数量',
                        params: [],
                        returns: {
                            type: 'integer',
                            description: '键值对的数量'
                        }
                    },
                    {
                        name: 'rawget',
                        description: '获取指定键的值',
                        params: [
                            {
                                name: 'key',
                                type: 'any',
                                description: '键'
                            }
                        ],
                        returns: {
                            type: 'any',
                            description: '键对应的值'
                        }
                    },
                    {
                        name: 'rawset',
                        description: '设置指定键的值',
                        params: [
                            {
                                name: 'key',
                                type: 'any',
                                description: '键'
                            },
                            {
                                name: 'value',
                                type: 'any',
                                description: '值'
                            }
                        ],
                        returns: {
                            type: 'void',
                            description: '无返回值'
                        }
                    }
                ],
                properties: []
            }
        ];

        // 初始化常量
        this.constants = [
            {
                name: 'PI',
                value: '3.14159',
                description: '圆周率',
                category: 'math'
            },
            {
                name: 'E',
                value: '2.71828',
                description: '自然常数',
                category: 'math'
            },
            {
                name: 'true',
                value: 'true',
                description: '布尔真值',
                category: 'boolean'
            },
            {
                name: 'false',
                value: 'false',
                description: '布尔假值',
                category: 'boolean'
            },
            {
                name: 'null',
                value: 'null',
                description: '空值',
                category: 'general'
            }
        ];
    }

    // 获取所有函数
    public getFunctions(): ApiFunction[] {
        return this.functions;
    }

    // 根据名称获取函数
    public getFunctionByName(name: string): ApiFunction | undefined {
        return this.functions.find(func => func.name === name);
    }

    // 获取所有类
    public getClasses(): ApiClass[] {
        return this.classes;
    }

    // 根据名称获取类
    public getClassByName(name: string): ApiClass | undefined {
        return this.classes.find(cls => cls.name === name);
    }

    // 获取所有常量
    public getConstants(): ApiConstant[] {
        return this.constants;
    }

    // 根据类别获取常量
    public getConstantsByCategory(category: string): ApiConstant[] {
        return this.constants.filter(constant => constant.category === category);
    }

    // 根据名称获取常量
    public getConstantByName(name: string): ApiConstant | undefined {
        return this.constants.find(constant => constant.name === name);
    }

    // 生成函数签名
    public generateFunctionSignature(func: ApiFunction): string {
        const params = func.params.map(param => {
            let paramStr = param.name;
            if (param.optional) {
                paramStr = `[${paramStr}`;
                if (param.defaultValue) {
                    paramStr += `=${param.defaultValue}`;
                }
                paramStr += ']';
            }
            return paramStr;
        }).join(', ');

        return `function ${func.name}(${params})${func.returns ? `: ${func.returns.type}` : ': void'}`;
    }

    // 生成类签名
    public generateClassSignature(cls: ApiClass): string {
        return `class ${cls.name}`;
    }

    // 生成属性签名
    public generatePropertySignature(prop: ApiProperty): string {
        return `property ${prop.name}: ${prop.type}`;
    }

    // 生成方法签名
    public generateMethodSignature(method: ApiFunction): string {
        const params = method.params.map(param => {
            let paramStr = param.name;
            if (param.optional) {
                paramStr = `[${paramStr}`;
                if (param.defaultValue) {
                    paramStr += `=${param.defaultValue}`;
                }
                paramStr += ']';
            }
            return paramStr;
        }).join(', ');

        return `function ${method.name}(${params})${method.returns ? `: ${method.returns.type}` : ': void'}`;
    }
}