import * as vscode from "vscode";

const WIZARD_COMPLETED_KEY = "acurity.setupWizardCompleted";

/**
 * Profile descriptions for the quick pick UI
 */
const PROFILE_OPTIONS = [
    {
        label: "$(star) Default",
        detail: "Balanced approach - warnings for style, errors for bugs",
        description: "Recommended for most projects",
        value: "default"
    },
    {
        label: "$(archive) Legacy",
        detail: "Relaxed rules for older codebases - disables ROBODOC requirements and naming rules",
        description: "Good for brownfield projects",
        value: "legacy"
    },
    {
        label: "$(shield) Strict",
        detail: "Strict enforcement - ROBODOC required, all naming rules as errors",
        description: "Best for new greenfield projects",
        value: "strict"
    }
];

/**
 * Run the setup wizard to configure Acurity extension for first-time users
 * @param {vscode.ExtensionContext} context - Extension context
 * @param {boolean} isFirstRun - Whether this is the first time the extension has run
 */
async function runSetupWizard(context, isFirstRun = false) {
    const config = vscode.workspace.getConfiguration();

    // Check if wizard has already been completed (only for manual invocations)
    if (!isFirstRun) {
        const hasCompleted = context.globalState.get(WIZARD_COMPLETED_KEY, false);
        
        if (hasCompleted) {
            const choice = await vscode.window.showInformationMessage(
                "You've already completed the setup wizard. What would you like to do?",
                "Re-run Setup Wizard",
                "Open Settings",
                "Cancel"
            );

            if (choice === "Open Settings") {
                openAcuritySettings();
                return;
            } else if (choice !== "Re-run Setup Wizard") {
                return;
            }
            // If "Re-run Setup Wizard" selected, continue with the wizard below
        }
    }

    // Step 1: Welcome Message
    const title = isFirstRun ? "Welcome to Acurity!" : "Acurity Setup Wizard";
    const message = isFirstRun 
        ? "Let's configure the extension for your needs. You can change these settings anytime."
        : "Configure Acurity extension settings.";

    const proceed = await vscode.window.showInformationMessage(
        message,
        { modal: false },
        "Continue",
        "Skip"
    );

    if (proceed !== "Continue") {
        return;
    }

    // Step 2: Standards Profile Selection
    const profileChoice = await vscode.window.showQuickPick(PROFILE_OPTIONS, {
        placeHolder: "Select a standards profile for validation rules",
        title: "Acurity Setup: Standards Profile",
        ignoreFocusOut: true
    });

    if (profileChoice) {
        await config.update(
            "acurity.rules.profile",
            profileChoice.value,
            vscode.ConfigurationTarget.Global
        );
    }

    // Step 2.5: Optional TXT file association
    await promptTxtAssociation();

    // Step 3: ROBODOC Validation
    const robodocChoice = await vscode.window.showQuickPick(
        [
            {
                label: "$(check) Enable ROBODOC Validation",
                detail: "Validate documentation blocks in Acurity files",
                value: true
            },
            {
                label: "$(x) Disable ROBODOC Validation",
                detail: "Skip documentation checks",
                value: false
            }
        ],
        {
            placeHolder: "Enable or disable ROBODOC documentation validation",
            title: "Acurity Setup: ROBODOC Validation",
            ignoreFocusOut: true
        }
    );

    if (robodocChoice) {
        await config.update(
            "acurity.robodoc.enabled",
            robodocChoice.value,
            vscode.ConfigurationTarget.Global
        );
    }

    // Step 4: Author Name (if ROBODOC enabled)
    if (robodocChoice?.value === true) {
        const setAuthor = await vscode.window.showQuickPick(
            [
                {
                    label: "$(person) Set Author Name",
                    detail: "Configure your name for ROBODOC @author tags",
                    value: true
                },
                {
                    label: "$(debug-step-over) Skip for Now",
                    detail: "You can set this later in settings",
                    value: false
                }
            ],
            {
                placeHolder: "Would you like to set your author name?",
                title: "Acurity Setup: Author Name",
                ignoreFocusOut: true
            }
        );

        if (setAuthor?.value === true) {
            const authorName = await vscode.window.showInputBox({
                title: "Acurity Setup: Author Name",
                prompt: "Enter the author name for ROBODOC templates",
                placeHolder: "e.g. John Smith",
                ignoreFocusOut: true
            });

            if (authorName && authorName.trim()) {
                await config.update(
                    "acurity.robodoc.authorName",
                    authorName.trim(),
                    vscode.ConfigurationTarget.Global
                );
            }
        }
    }

    // Step 5: Completion
    await context.globalState.update(WIZARD_COMPLETED_KEY, true);

    const viewSettings = await vscode.window.showInformationMessage(
        "Setup complete! You can adjust these settings anytime using the 'Acurity: Open Settings' command.",
        "View Settings",
        "Done"
    );

    if (viewSettings === "View Settings") {
        openAcuritySettings();
    }
}

/**
 * Open VS Code settings filtered to Acurity extension settings
 */
function openAcuritySettings() {
    vscode.commands.executeCommand("workbench.action.openSettings", "@ext:jibbius.acurity");
}

/**
 * Prompt user to optionally associate .txt files with the Acurity language.
 */
async function promptTxtAssociation() {
    const existingAssociation = vscode.workspace
        .getConfiguration()
        .get("files.associations", {})["*.txt"];

    const promptMessage = existingAssociation && existingAssociation !== "acurity"
        ? `Current '*.txt' association is '${existingAssociation}'. Set it to 'acurity' instead?`
        : "Acurity commonly uses .txt files. Make '*.txt' open as Acurity Architect by default?";

    const choice = await vscode.window.showQuickPick(
        [
            {
                label: "$(check) Yes, associate *.txt with Acurity",
                detail: "Recommended for Acurity-heavy workspaces",
                value: "associate"
            },
            {
                label: "$(debug-step-over) Skip for now",
                detail: "Keep your existing text file behavior",
                value: "skip"
            }
        ],
        {
            placeHolder: promptMessage,
            title: "Acurity Setup: TXT File Association",
            ignoreFocusOut: true
        }
    );

    if (choice?.value === "associate") {
        const changed = await associateTxtFilesWithAcurity(vscode.ConfigurationTarget.Global);

        if (changed) {
            await vscode.window.showInformationMessage(
                "Associated '*.txt' files with Acurity Architect.",
                "Open Settings"
            ).then((selection) => {
                if (selection === "Open Settings") {
                    openAcuritySettings();
                }
            });
        }
    }
}

/**
 * Update files.associations so .txt files use the Acurity language id.
 * @param {vscode.ConfigurationTarget} target - Where to save settings.
 * @returns {Promise<boolean>} True if settings changed.
 */
async function associateTxtFilesWithAcurity(target = vscode.ConfigurationTarget.Global) {
    const config = vscode.workspace.getConfiguration();
    const associations = config.get("files.associations", {});
    const alreadyAssociated = associations["*.txt"] === "acurity";

    if (alreadyAssociated) {
        return false;
    }

    const updatedAssociations = {
        ...associations,
        "*.txt": "acurity"
    };

    await config.update("files.associations", updatedAssociations, target);
    return true;
}

/**
 * Check if this is the first run and optionally show the wizard
 * @param {vscode.ExtensionContext} context - Extension context
 */
async function checkFirstRun(context) {
    const hasCompleted = context.globalState.get(WIZARD_COMPLETED_KEY, false);
    
    if (!hasCompleted) {
        // Small delay to avoid showing immediately on activation
        setTimeout(async () => {
            try {
                await runSetupWizard(context, true);
            } catch (err) {
                console.error("checkFirstRun: runSetupWizard failed", err);
                vscode.window.showErrorMessage(`Setup wizard failed to start: ${err.message}`);
            }
        }, 2000);
    }
}

/**
 * Register setup wizard commands
 * @param {vscode.ExtensionContext} context - Extension context
 */
function registerSetupCommands(context) {
    context.subscriptions.push(
        vscode.commands.registerCommand("acurity.runSetupWizard", () => {
            runSetupWizard(context, false);
        })
    );

    context.subscriptions.push(
        vscode.commands.registerCommand("acurity.openSettings", () => {
            openAcuritySettings();
        })
    );

    context.subscriptions.push(
        vscode.commands.registerCommand("acurity.associateTxtFiles", async () => {
            const changed = await associateTxtFilesWithAcurity(vscode.ConfigurationTarget.Global);

            if (changed) {
                vscode.window.showInformationMessage("Associated '*.txt' files with Acurity Architect.");
            } else {
                vscode.window.showInformationMessage("'*.txt' is already associated with Acurity Architect.");
            }
        })
    );
}

export {
    registerSetupCommands,
    checkFirstRun,
    runSetupWizard,
    openAcuritySettings
};
