/**
 * Completion provider for Acurity Architect macros.
 */

import * as vscode from "vscode";
import { LANGUAGE_ID, MACRO_TRIGGER_CHARACTER } from "../../core/src/constants.js";
import { collectDocumentFacts } from "../../core/src/analysis/documentFacts.js";

function buildMacroInsertText(macroName, params) {
    if (!params || params.length === 0) {
        return macroName;
    }
    return `${macroName}(${params.join(", ")})`;
}

function createMacroCompletionItems(document, position) {
    const linePrefix = document.lineAt(position.line).text.slice(0, position.character);

    // No completions inside comments
    if (linePrefix.trimStart().startsWith("//")) {
        return [];
    }

    const prefixMatch = linePrefix.match(/([A-Za-z_][A-Za-z0-9_]*)$/);
    const typedPrefix = prefixMatch ? prefixMatch[1] : "";

    const facts = collectDocumentFacts(document);
    const entries = Object.values(facts.macroCatalog || {});
    if (entries.length === 0) {
        return [];
    }

    const upperPrefix = typedPrefix.toUpperCase();
    const filteredEntries = upperPrefix
        ? entries.filter((entry) => entry.declaredName.toUpperCase().startsWith(upperPrefix))
        : entries;

    return filteredEntries.map((entry) => {
        const item = new vscode.CompletionItem(entry.declaredName, vscode.CompletionItemKind.Function);
        item.insertText = buildMacroInsertText(entry.declaredName, entry.params);
        item.detail = entry.params.length > 0
            ? `MACRO (${entry.params.length} parameter${entry.params.length === 1 ? "" : "s"})`
            : "MACRO";

        const markdown = new vscode.MarkdownString();
        markdown.appendCodeblock(`MACRO ${entry.declaredName}${entry.params.length ? `(${entry.params.join(", ")})` : ""}`, "acurity");
        markdown.appendMarkdown("\n**Expands to:**\n");
        markdown.appendCodeblock(entry.body || "", "text");
        markdown.appendMarkdown(`\nDeclared at line ${entry.lineIndex + 1}.`);
        item.documentation = markdown;
        item.sortText = `0_${entry.declaredName.toUpperCase()}`;
        return item;
    });
}

function initializeCompletionProvider(context) {
    const completionProvider = vscode.languages.registerCompletionItemProvider(
        LANGUAGE_ID,
        {
            provideCompletionItems(document, position) {
                return createMacroCompletionItems(document, position);
            }
        },
        MACRO_TRIGGER_CHARACTER
    );

    context.subscriptions.push(completionProvider);
}

export {
    initializeCompletionProvider,
    createMacroCompletionItems,
    buildMacroInsertText
};
