"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runInstallAuthFlow = runInstallAuthFlow;
const inquirer_1 = __importDefault(require("inquirer"));
const chalk_1 = __importDefault(require("chalk"));
const feishu_auth_1 = require("./feishu-auth");
/**
 * Handles the interactive installation flow for Feishu configuration.
 *
 * @param currentAppId Optional existing App ID
 * @param currentAppSecret Optional existing App Secret
 * @returns Promise<AuthConfig> The validated App ID and App Secret
 */
async function runInstallAuthFlow(currentAppId, currentAppSecret) {
    // Scenario 1: No existing App ID
    if (!currentAppId) {
        return handleNewInstallation();
    }
    // Scenario 2: Existing App ID
    console.log(chalk_1.default.blue(`Found existing App ID: ${currentAppId}`));
    const { action } = await inquirer_1.default.prompt([
        {
            type: 'list',
            name: 'action',
            message: 'What would you like to do? (请选择操作)',
            choices: [
                { name: '新增机器人 (Create new Feishu bot)', value: 'create_new' },
                { name: '使用已有机器人 (Use existing bot)', value: 'use_existing' }
            ]
        }
    ]);
    if (action === 'create_new') {
        return handleNewInstallation();
    }
    else {
        // use_existing
        return handleExistingInstallation(currentAppId, currentAppSecret);
    }
}
async function showOptimizationPrompt(appId) {
    const optimizeUrl = `https://open.feishu.cn/page/openclaw?clientID=${appId}`;
    console.log(chalk_1.default.cyan('\nTo complete your Feishu bot\'s setup in one click, open this link (复制该链接到浏览器中打开，一键完善飞书机器人的配置):'));
    console.log(chalk_1.default.underline(optimizeUrl));
    console.log('\n');
    // Wait for user to acknowledge optimization
    await inquirer_1.default.prompt([
        {
            type: 'confirm',
            name: 'done',
            message: 'Press Enter once you have finished (完成后请按回车)',
            default: true
        }
    ]);
}
async function handleNewInstallation() {
    console.log(chalk_1.default.cyan('\nTo create your Feishu bot in one click, open this link (复制该链接到浏览器中打开，一键创建飞书机器人):'));
    const createUrl = 'https://open.feishu.cn/page/openclaw';
    console.log(chalk_1.default.underline(createUrl));
    console.log('\n');
    return promptAndValidateCredentials();
}
async function handleExistingInstallation(appId, appSecret) {
    let validatedSecret = appSecret;
    // If we don't have a secret, or we need to validate, ensure we have one to test
    if (!validatedSecret) {
        const response = await inquirer_1.default.prompt([
            {
                type: 'password',
                name: 'inputSecret',
                message: 'Please enter your App Secret (请输入 App Secret) [Press <Enter> to confirm]:',
                mask: '*',
                validate: (input) => input.length > 0 || 'App Secret cannot be empty'
            }
        ]);
        validatedSecret = response.inputSecret;
    }
    console.log(chalk_1.default.yellow('Verifying credentials (正在校验凭证)...'));
    const isValid = await (0, feishu_auth_1.validateAppCredentials)(appId, validatedSecret);
    if (isValid) {
        console.log(chalk_1.default.green('✓ Credentials verified successfully (凭证校验成功).'));
        // Prompt for optimization
        await showOptimizationPrompt(appId);
        return { appId, appSecret: validatedSecret };
    }
    else {
        console.log(chalk_1.default.red('✗ Invalid App ID or App Secret (无效的 App ID 或 App Secret).'));
        // Fallback to manual entry for both, pre-filling App ID.
        // IMPORTANT: After manual entry success, we MUST also show the optimization prompt.
        const creds = await promptAndValidateCredentials(appId);
        await showOptimizationPrompt(creds.appId);
        return creds;
    }
}
async function promptAndValidateCredentials(defaultAppId) {
    while (true) {
        const answers = await inquirer_1.default.prompt([
            {
                type: 'input',
                name: 'appId',
                message: 'Please enter your App ID (请输入 App ID):',
                default: defaultAppId,
                validate: (input) => input.length > 0 || 'App ID cannot be empty'
            },
            {
                type: 'password',
                name: 'appSecret',
                message: 'Please enter your App Secret (请输入 App Secret) [Press <Enter> to confirm]:',
                mask: '*',
                validate: (input) => input.length > 0 || 'App Secret cannot be empty'
            }
        ]);
        console.log(chalk_1.default.yellow('Verifying credentials (正在校验凭证)...'));
        const isValid = await (0, feishu_auth_1.validateAppCredentials)(answers.appId, answers.appSecret);
        if (isValid) {
            console.log(chalk_1.default.green('✓ Credentials verified successfully (凭证校验成功).'));
            return { appId: answers.appId, appSecret: answers.appSecret };
        }
        else {
            console.log(chalk_1.default.red('✗ Invalid App ID or App Secret. Please try again (App ID 或 App Secret 无效，请重试).'));
            // Update defaultAppId for next iteration so they don't have to re-type if it was correct
            defaultAppId = answers.appId;
        }
    }
}
//# sourceMappingURL=install-prompts.js.map