"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProfileConfigManager = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const chalk_1 = __importDefault(require("chalk"));
const inquirer_1 = __importDefault(require("inquirer"));
class ProfileConfigManager {
    configPath;
    constructor(homeDir) {
        const home = homeDir || os.homedir();
        this.configPath = path.join(home, '.majk-chat', 'profiles', 'config.json');
    }
    async loadConfig() {
        if (!await fs.pathExists(this.configPath)) {
            return { profiles: {} };
        }
        try {
            return await fs.readJson(this.configPath);
        }
        catch (error) {
            console.warn(chalk_1.default.yellow(`Warning: Could not parse config file: ${error}`));
            return { profiles: {} };
        }
    }
    async saveConfig(config) {
        await fs.ensureDir(path.dirname(this.configPath));
        await fs.writeJson(this.configPath, config, { spaces: 2 });
    }
    async getProfile(profileName = 'default') {
        const config = await this.loadConfig();
        return config.profiles[profileName] || null;
    }
    async setProfile(profileName, profileConfig) {
        const config = await this.loadConfig();
        config.profiles[profileName] = profileConfig;
        await this.saveConfig(config);
    }
    async deleteProfile(profileName) {
        const config = await this.loadConfig();
        if (config.profiles[profileName]) {
            delete config.profiles[profileName];
            await this.saveConfig(config);
            return true;
        }
        return false;
    }
    async listProfiles() {
        const config = await this.loadConfig();
        return Object.keys(config.profiles);
    }
    /**
     * Get provider credentials from profile for use with existing CredentialManager
     */
    async getProviderCredentials(provider, profileName = 'default') {
        const profile = await this.getProfile(profileName);
        if (!profile || !profile.providers[provider]) {
            return null;
        }
        const providerConfig = profile.providers[provider];
        switch (provider) {
            case 'openai':
                const openaiConfig = providerConfig;
                return {
                    apiKey: openaiConfig?.apiKey,
                    organizationId: openaiConfig?.organizationId
                };
            case 'anthropic':
                const anthropicConfig = providerConfig;
                return {
                    apiKey: anthropicConfig?.apiKey
                };
            case 'azure-openai':
                const azureConfig = providerConfig;
                return {
                    apiKey: azureConfig?.apiKey,
                    endpoint: azureConfig?.endpoint,
                    deploymentName: azureConfig?.deploymentName
                };
            case 'bedrock':
                const bedrockConfig = providerConfig;
                return {
                    accessKeyId: bedrockConfig?.accessKeyId,
                    secretAccessKey: bedrockConfig?.secretAccessKey,
                    sessionToken: bedrockConfig?.sessionToken,
                    region: bedrockConfig?.region || 'us-east-1',
                    bearerToken: bedrockConfig?.bearerToken
                };
            default:
                return null;
        }
    }
    /**
     * Interactive configuration for a provider
     */
    async configureProvider(provider, profileName = 'default', skipValidation = false) {
        console.log(chalk_1.default.cyan(`\nConfiguring ${provider} for profile: ${chalk_1.default.bold(profileName)}`));
        const profile = await this.getProfile(profileName) || { providers: {} };
        switch (provider) {
            case 'openai':
                await this.configureOpenAI(profile, skipValidation);
                break;
            case 'anthropic':
                await this.configureAnthropic(profile, skipValidation);
                break;
            case 'azure-openai':
                await this.configureAzureOpenAI(profile, skipValidation);
                break;
            case 'bedrock':
                await this.configureBedrock(profile, skipValidation);
                break;
            default:
                throw new Error(`Unsupported provider: ${provider}`);
        }
        await this.setProfile(profileName, profile);
        console.log(chalk_1.default.green(`\n✓ ${provider} configuration saved to profile: ${profileName}`));
    }
    /**
     * Direct configuration without interaction
     */
    async setDirectConfig(options) {
        const profileName = options.profile || 'default';
        const profile = await this.getProfile(profileName) || { providers: {} };
        // OpenAI
        if (options.setOpenaiKey) {
            profile.providers.openai = {
                apiKey: options.setOpenaiKey,
                organizationId: options.openaiOrgId
            };
            if (!options.skipValidation) {
                await this.validateProvider('openai', profile.providers.openai, profileName);
            }
        }
        // Anthropic
        if (options.setAnthropicKey) {
            profile.providers.anthropic = {
                apiKey: options.setAnthropicKey
            };
            if (!options.skipValidation) {
                await this.validateProvider('anthropic', profile.providers.anthropic, profileName);
            }
        }
        // Azure OpenAI
        if (options.setAzureOpenaiKey && options.azureOpenaiEndpoint && options.azureOpenaiDeployment) {
            profile.providers['azure-openai'] = {
                apiKey: options.setAzureOpenaiKey,
                endpoint: options.azureOpenaiEndpoint,
                deploymentName: options.azureOpenaiDeployment
            };
            if (!options.skipValidation) {
                await this.validateProvider('azure-openai', profile.providers['azure-openai'], profileName);
            }
        }
        // Bedrock
        if (options.setBedrock) {
            if (options.bedrockBearerToken) {
                // Bearer token authentication
                profile.providers.bedrock = {
                    bearerToken: options.bedrockBearerToken,
                    region: options.awsRegion || 'us-east-1'
                };
            }
            else if (options.awsAccessKeyId && options.awsSecretAccessKey) {
                // Traditional AWS credentials
                profile.providers.bedrock = {
                    accessKeyId: options.awsAccessKeyId,
                    secretAccessKey: options.awsSecretAccessKey,
                    sessionToken: options.awsSessionToken,
                    region: options.awsRegion || 'us-east-1'
                };
            }
            else {
                throw new Error('Bedrock configuration requires either bearerToken or accessKeyId+secretAccessKey');
            }
            if (!options.skipValidation) {
                await this.validateProvider('bedrock', profile.providers.bedrock, profileName);
            }
        }
        await this.setProfile(profileName, profile);
        console.log(chalk_1.default.green(`✓ Configuration saved to profile: ${profileName}`));
    }
    async configureOpenAI(profile, skipValidation) {
        const response = await inquirer_1.default.prompt([
            {
                type: 'password',
                name: 'apiKey',
                message: 'OpenAI API Key:',
                validate: (value) => value.length > 0 || 'API key is required',
                mask: '*'
            },
            {
                type: 'input',
                name: 'organizationId',
                message: 'OpenAI Organization ID (optional):'
            }
        ]);
        const config = {
            apiKey: response.apiKey,
            organizationId: response.organizationId || undefined
        };
        if (!skipValidation) {
            await this.validateProvider('openai', config, 'temp');
        }
        profile.providers.openai = config;
    }
    async configureAnthropic(profile, skipValidation) {
        const response = await inquirer_1.default.prompt([
            {
                type: 'password',
                name: 'apiKey',
                message: 'Anthropic API Key:',
                validate: (value) => value.length > 0 || 'API key is required',
                mask: '*'
            }
        ]);
        const config = {
            apiKey: response.apiKey
        };
        if (!skipValidation) {
            await this.validateProvider('anthropic', config, 'temp');
        }
        profile.providers.anthropic = config;
    }
    async configureAzureOpenAI(profile, skipValidation) {
        const response = await inquirer_1.default.prompt([
            {
                type: 'password',
                name: 'apiKey',
                message: 'Azure OpenAI API Key:',
                validate: (value) => value.length > 0 || 'API key is required',
                mask: '*'
            },
            {
                type: 'input',
                name: 'endpoint',
                message: 'Azure OpenAI Endpoint:',
                validate: (value) => value.length > 0 || 'Endpoint is required'
            },
            {
                type: 'input',
                name: 'deploymentName',
                message: 'Azure OpenAI Deployment Name:',
                validate: (value) => value.length > 0 || 'Deployment name is required'
            }
        ]);
        const config = {
            apiKey: response.apiKey,
            endpoint: response.endpoint,
            deploymentName: response.deploymentName
        };
        if (!skipValidation) {
            await this.validateProvider('azure-openai', config, 'temp');
        }
        profile.providers['azure-openai'] = config;
    }
    async configureBedrock(profile, skipValidation) {
        // First ask which authentication method to use
        const authChoice = await inquirer_1.default.prompt([{
                type: 'list',
                name: 'authMethod',
                message: 'Choose Bedrock authentication method:',
                choices: [
                    { name: 'API Key (Bearer Token)', value: 'bearer' },
                    { name: 'AWS Credentials (Access Key + Secret)', value: 'credentials' }
                ]
            }]);
        let config = {};
        if (authChoice.authMethod === 'bearer') {
            // Bearer token authentication
            const response = await inquirer_1.default.prompt([
                {
                    type: 'password',
                    name: 'bearerToken',
                    message: 'AWS Bedrock API Key (Bearer Token):',
                    validate: (value) => value.length > 0 || 'Bearer token is required',
                    mask: '*'
                },
                {
                    type: 'input',
                    name: 'region',
                    message: 'AWS Region:',
                    default: 'us-east-1'
                }
            ]);
            config = {
                bearerToken: response.bearerToken,
                region: response.region
            };
        }
        else {
            // Traditional AWS credentials
            const response = await inquirer_1.default.prompt([
                {
                    type: 'password',
                    name: 'accessKeyId',
                    message: 'AWS Access Key ID:',
                    validate: (value) => value.length > 0 || 'Access Key ID is required',
                    mask: '*'
                },
                {
                    type: 'password',
                    name: 'secretAccessKey',
                    message: 'AWS Secret Access Key:',
                    validate: (value) => value.length > 0 || 'Secret Access Key is required',
                    mask: '*'
                },
                {
                    type: 'password',
                    name: 'sessionToken',
                    message: 'AWS Session Token (optional):',
                    mask: '*'
                },
                {
                    type: 'input',
                    name: 'region',
                    message: 'AWS Region:',
                    default: 'us-east-1'
                }
            ]);
            config = {
                accessKeyId: response.accessKeyId,
                secretAccessKey: response.secretAccessKey,
                sessionToken: response.sessionToken || undefined,
                region: response.region
            };
        }
        if (!skipValidation) {
            await this.validateProvider('bedrock', config, 'temp');
        }
        profile.providers.bedrock = config;
    }
    /**
     * Validate provider configuration by making a test API call
     */
    async validateProvider(provider, config, _profileName) {
        console.log(chalk_1.default.yellow(`\nValidating ${provider} credentials...`));
        try {
            // Import majk-chat-core dynamically to avoid circular dependencies
            const { MajkChatBuilder } = await Promise.resolve().then(() => __importStar(require('@majkapp/majk-chat-core')));
            const builder = new MajkChatBuilder();
            // Configure the specific provider
            switch (provider) {
                case 'openai':
                    builder.withOpenAI(config);
                    break;
                case 'anthropic':
                    builder.withAnthropic(config);
                    break;
                case 'azure-openai':
                    builder.withAzureOpenAI(config);
                    break;
                case 'bedrock':
                    builder.withBedrock(config);
                    break;
            }
            const chat = builder.build();
            const providerAdapter = chat.getProvider(provider);
            // Try to list models as a quick validation
            await providerAdapter.listModels({
                requestId: `validation-${Date.now()}`
            });
            console.log(chalk_1.default.green(`✓ ${provider} credentials are valid`));
        }
        catch (error) {
            console.log(chalk_1.default.red(`✗ ${provider} credentials validation failed:`));
            console.log(chalk_1.default.red(`  ${error instanceof Error ? error.message : error}`));
            const response = await inquirer_1.default.prompt([{
                    type: 'confirm',
                    name: 'proceed',
                    message: 'Save configuration anyway?',
                    default: false
                }]);
            if (!response.proceed) {
                throw new Error('Configuration cancelled due to validation failure');
            }
        }
    }
    /**
     * Test all providers in a profile
     */
    async testProfile(profileName) {
        const profile = await this.getProfile(profileName);
        if (!profile) {
            throw new Error(`Profile '${profileName}' not found`);
        }
        const results = [];
        for (const [provider, config] of Object.entries(profile.providers)) {
            if (config) {
                const result = await this.testProvider(provider, profileName);
                results.push(result);
            }
        }
        return results;
    }
    /**
     * Test specific provider in a profile
     */
    async testProvider(provider, profileName = 'default') {
        const config = await this.getProviderCredentials(provider, profileName);
        if (!config) {
            return {
                provider,
                profile: profileName,
                valid: false,
                error: 'No configuration found'
            };
        }
        try {
            const { MajkChatBuilder } = await Promise.resolve().then(() => __importStar(require('@majkapp/majk-chat-core')));
            const builder = new MajkChatBuilder();
            switch (provider) {
                case 'openai':
                    builder.withOpenAI(config);
                    break;
                case 'anthropic':
                    builder.withAnthropic(config);
                    break;
                case 'azure-openai':
                    builder.withAzureOpenAI(config);
                    break;
                case 'bedrock':
                    builder.withBedrock(config);
                    break;
                default:
                    throw new Error(`Unsupported provider: ${provider}`);
            }
            const chat = builder.build();
            const providerAdapter = chat.getProvider(provider);
            const modelsResponse = await providerAdapter.listModels({
                requestId: `test-${Date.now()}`
            });
            const firstModel = modelsResponse.data[0]?.id || 'unknown';
            return {
                provider,
                profile: profileName,
                valid: true,
                model: firstModel
            };
        }
        catch (error) {
            return {
                provider,
                profile: profileName,
                valid: false,
                error: error instanceof Error ? error.message : String(error)
            };
        }
    }
    /**
     * Test all profiles
     */
    async testAllProfiles() {
        const profileNames = await this.listProfiles();
        const results = [];
        for (const profileName of profileNames) {
            const profileResults = await this.testProfile(profileName);
            results.push(...profileResults);
        }
        return results;
    }
}
exports.ProfileConfigManager = ProfileConfigManager;
//# sourceMappingURL=profile-config.js.map