import * as vscode from 'vscode';
import { FunctionCacheManager, FunctionInfo } from '../functionExtractor';
import { ApiParser, ApiFunction, ApiClass, ApiConstant } from './apiParser';

// 悬停信息提供者类
export class HoverProvider implements vscode.HoverProvider {
    private cacheManager: FunctionCacheManager;
    private apiParser: ApiParser;

    constructor(cacheManager: FunctionCacheManager) {
        this.cacheManager = cacheManager;
        this.apiParser = ApiParser.getInstance();
    }

    // 提供悬停时显示的信息
    async provideHover(
        document: vscode.TextDocument,
        position: vscode.Position,
        token: vscode.CancellationToken
    ): Promise<vscode.Hover | undefined> {
        // 检查是否在注释中，如果在注释中则不提供悬停信息
        const line = document.lineAt(position.line);
        const commentIndex = line.text.indexOf('//');
        if (commentIndex >= 0 && position.character > commentIndex) {
            return undefined;
        }

        // 获取鼠标悬停位置的单词范围
        const range = document.getWordRangeAtPosition(position);
        if (!range) {
            return undefined;
        }

        // 获取单词
        const word = document.getText(range);

        // 首先检查是否是API函数
        const apiFunction = this.apiParser.getFunctionByName(word);
        if (apiFunction) {
            const signature = this.apiParser.generateFunctionSignature(apiFunction);
            let hoverContent = `**内置函数**: \`${signature}\`\n\n`;
            hoverContent += `${apiFunction.description}\n\n`;

            if (apiFunction.params.length > 0) {
                hoverContent += `**参数**:\n`;
                apiFunction.params.forEach(param => {
                    hoverContent += `- \`${param.name}: ${param.type}\`${param.optional ? ' (可选)' : ''} - ${param.description}\n`;
                });
            }

            if (apiFunction.returns) {
                hoverContent += `\n**返回值**: \`${apiFunction.returns.type}\` - ${apiFunction.returns.description}`;
            }

            return new vscode.Hover(new vscode.MarkdownString(hoverContent), range);
        }

        // 检查是否是API类
        const apiClass = this.apiParser.getClassByName(word);
        if (apiClass) {
            const signature = this.apiParser.generateClassSignature(apiClass);
            let hoverContent = `**内置类**: \`${signature}\`\n\n`;
            hoverContent += `${apiClass.description}\n\n`;

            if (apiClass.methods.length > 0) {
                hoverContent += `**方法**:\n`;
                apiClass.methods.forEach(method => {
                    const methodSignature = this.apiParser.generateMethodSignature(method);
                    hoverContent += `- \`${methodSignature}\` - ${method.description}\n`;
                });
            }

            if (apiClass.properties.length > 0) {
                hoverContent += `\n**属性**:\n`;
                apiClass.properties.forEach(prop => {
                    const propSignature = this.apiParser.generatePropertySignature(prop);
                    hoverContent += `- \`${propSignature}\` - ${prop.description}\n`;
                });
            }

            return new vscode.Hover(new vscode.MarkdownString(hoverContent), range);
        }

        // 检查是否是API常量
        const apiConstant = this.apiParser.getConstantByName(word);
        if (apiConstant) {
            let hoverContent = `**常量**: \`${apiConstant.name}\`\n\n`;
            hoverContent += `值: ${apiConstant.value}\n\n`;
            hoverContent += `${apiConstant.description}\n\n`;
            hoverContent += `类别: ${apiConstant.category}`;

            return new vscode.Hover(new vscode.MarkdownString(hoverContent), range);
        }

        // 查找函数信息
        const functions = this.cacheManager.findFunctionsByName(word);
        if (functions.length > 0) {
            // 创建悬停信息
            let hoverContent = '';

            if (functions.length === 1) {
                // 单个函数
                const func = functions[0];
                hoverContent = `**函数**: \`${func.signature}\`\n\n`;
                hoverContent += `**文件**: ${func.filePath}\n\n`;
                hoverContent += `**行号**: ${func.lineNumber}`;
            } else {
                // 多个同名函数
                hoverContent = `**函数**: ${word}\n\n`;
                hoverContent += `在多个文件中定义:\n\n`;
                functions.forEach(func => {
                    hoverContent += `- \`${func.signature}\` (${func.filePath}:${func.lineNumber})\n`;
                });
            }

            return new vscode.Hover(new vscode.MarkdownString(hoverContent), range);
        }

        // 检查是否是关键字
        const keywordInfo = this.getKeywordInfo(word);
        if (keywordInfo) {
            return new vscode.Hover(new vscode.MarkdownString(keywordInfo), range);
        }

        // 检查是否是常量
        const constantInfo = this.getConstantInfo(word);
        if (constantInfo) {
            return new vscode.Hover(new vscode.MarkdownString(constantInfo), range);
        }

        return undefined;
    }

    // 获取关键字信息
    private getKeywordInfo(word: string): string | undefined {
        const keywordMap: { [key: string]: string } = {
            'if': '**条件语句**\n\n用于条件执行代码块',
            'else': '**条件语句**\n\n与if语句配合使用，当if条件不满足时执行',
            'while': '**循环语句**\n\n当条件为真时重复执行代码块',
            'for': '**循环语句**\n\n用于循环执行代码块',
            'foreach': '**循环语句**\n\n遍历数组或表中的每个元素',
            'function': '**函数定义**\n\n用于定义函数',
            'local': '**变量声明**\n\n声明局部变量',
            'return': '**返回语句**\n\n从函数中返回值',
            'class': '**类定义**\n\n用于定义类',
            'extends': '**继承**\n\n用于指定类的父类',
            'constructor': '**构造函数**\n\n类的构造函数',
            'null': '**空值**\n\n表示空值',
            'true': '**布尔值**\n\n表示真值',
            'false': '**布尔值**\n\n表示假值'
        };

        return keywordMap[word];
    }

    // 获取常量信息
    private getConstantInfo(word: string): string | undefined {
        const constantMap: { [key: string]: string } = {
            'PI': '**数学常量**\n\n圆周率 π ≈ 3.14159',
            'E': '**数学常量**\n\n自然常数 e ≈ 2.71828',
            'RAND_MAX': '**随机数**\n\n随机数生成器的最大值',
            'CHAR_BIT': '**字符**\n\n一个字节的位数',
            'CHAR_MAX': '**字符**\n\nchar类型的最大值',
            'CHAR_MIN': '**字符**\n\nchar类型的最小值',
            'SHRT_MAX': '**短整型**\n\nshort类型的最大值',
            'SHRT_MIN': '**短整型**\n\nshort类型的最小值',
            'INT_MAX': '**整型**\n\nint类型的最大值',
            'INT_MIN': '**整型**\n\nint类型的最小值',
            'LONG_MAX': '**长整型**\n\nlong类型的最大值',
            'LONG_MIN': '**长整型**\n\nlong类型的最小值',
            'FLT_MAX': '**浮点型**\n\nfloat类型的最大值',
            'FLT_MIN': '**浮点型**\n\nfloat类型的最小值',
            'DBL_MAX': '**双精度浮点型**\n\ndouble类型的最大值',
            'DBL_MIN': '**双精度浮点型**\n\ndouble类型的最小值'
        };

        return constantMap[word];
    }
}