/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { GoogleGenAI } from '@google/genai';
import { createCodeAssistContentGenerator } from '../code_assist/codeAssist.js';
import { DEFAULT_ARC_MODEL } from '../config/models.js';
import { InstallationManager } from '../utils/installationManager.js';
import { LoggingContentGenerator } from './loggingContentGenerator.js';
export var AuthType;
(function (AuthType) {
    AuthType["LOGIN_WITH_GOOGLE"] = "oauth-personal";
    AuthType["USE_GEMINI"] = "gemini-api-key";
    AuthType["USE_VERTEX_AI"] = "vertex-ai";
    AuthType["CLOUD_SHELL"] = "cloud-shell";
    AuthType["USE_OPENAI"] = "openai";
    AuthType["QWEN_OAUTH"] = "qwen-oauth";
    AuthType["CLAUDE_CODE_OAUTH"] = "claude-code-oauth";
})(AuthType || (AuthType = {}));
export function createContentGeneratorConfig(config, authType, generationConfig) {
    const newContentGeneratorConfig = {
        ...(generationConfig || {}),
        authType,
        proxy: config?.getProxy(),
    };
    if (authType === AuthType.QWEN_OAUTH) {
        // For Qwen OAuth, we'll handle the API key dynamically in createContentGenerator
        // Set a special marker to indicate this is Qwen OAuth
        return {
            ...newContentGeneratorConfig,
            model: DEFAULT_ARC_MODEL,
            apiKey: 'QWEN_OAUTH_DYNAMIC_TOKEN',
        };
    }
    if (authType === AuthType.USE_OPENAI) {
        if (!newContentGeneratorConfig.apiKey) {
            throw new Error('OpenAI API key is required');
        }
        return {
            ...newContentGeneratorConfig,
            model: newContentGeneratorConfig?.model || 'qwen3-coder-plus',
        };
    }
    return {
        ...newContentGeneratorConfig,
        model: newContentGeneratorConfig?.model || DEFAULT_ARC_MODEL,
    };
}
export async function createContentGenerator(config, gcConfig, sessionId) {
    const version = process.env['CLI_VERSION'] || process.version;
    const userAgent = `ArcCLI/${version} (${process.platform}; ${process.arch})`;
    const baseHeaders = {
        'User-Agent': userAgent,
    };
    if (config.authType === AuthType.LOGIN_WITH_GOOGLE ||
        config.authType === AuthType.CLOUD_SHELL) {
        const httpOptions = { headers: baseHeaders };
        return new LoggingContentGenerator(await createCodeAssistContentGenerator(httpOptions, config.authType, gcConfig, sessionId), gcConfig);
    }
    if (config.authType === AuthType.USE_GEMINI ||
        config.authType === AuthType.USE_VERTEX_AI) {
        let headers = { ...baseHeaders };
        if (gcConfig?.getUsageStatisticsEnabled()) {
            const installationManager = new InstallationManager();
            const installationId = installationManager.getInstallationId();
            headers = {
                ...headers,
                'x-gemini-api-privileged-user-id': `${installationId}`,
            };
        }
        const httpOptions = { headers };
        const googleGenAI = new GoogleGenAI({
            apiKey: config.apiKey === '' ? undefined : config.apiKey,
            vertexai: config.vertexai,
            httpOptions,
        });
        return new LoggingContentGenerator(googleGenAI.models, gcConfig);
    }
    if (config.authType === AuthType.USE_OPENAI) {
        if (!config.apiKey) {
            throw new Error('OpenAI API key is required');
        }
        // Import OpenAIContentGenerator dynamically to avoid circular dependencies
        const { createOpenAIContentGenerator } = await import('./openaiContentGenerator/index.js');
        // Always use OpenAIContentGenerator, logging is controlled by enableOpenAILogging flag
        return createOpenAIContentGenerator(config, gcConfig);
    }
    if (config.authType === AuthType.QWEN_OAUTH) {
        // Import required classes dynamically
        const { getQwenOAuthClient: getQwenOauthClient } = await import('../qwen/qwenOAuth2.js');
        const { QwenContentGenerator } = await import('../qwen/qwenContentGenerator.js');
        try {
            // Get the Qwen OAuth client (now includes integrated token management)
            const qwenClient = await getQwenOauthClient(gcConfig);
            // Create the content generator with dynamic token management
            return new QwenContentGenerator(qwenClient, config, gcConfig);
        }
        catch (error) {
            throw new Error(`Failed to initialize Qwen: ${error instanceof Error ? error.message : String(error)}`);
        }
    }
    if (config.authType === AuthType.CLAUDE_CODE_OAUTH) {
        // Claude Code OAuth uses Anthropic API with OAuth tokens or API key
        // Check for OAuth tokens first, then fall back to API key
        const claudeCodeToken = process.env['CLAUDE_CODE_OAUTH_TOKEN'];
        const claudeAccessToken = process.env['CLAUDE_ACCESS_TOKEN'];
        const anthropicApiKey = process.env['ANTHROPIC_API_KEY'];
        let apiKey;
        if (claudeCodeToken) {
            apiKey = claudeCodeToken;
        }
        else if (claudeAccessToken) {
            apiKey = claudeAccessToken;
        }
        else if (anthropicApiKey) {
            apiKey = anthropicApiKey;
        }
        else {
            throw new Error('Claude Code OAuth requires authentication. Please set one of:\n' +
                '  - ANTHROPIC_API_KEY (for API key authentication)\n' +
                '  - CLAUDE_CODE_OAUTH_TOKEN (for OAuth token)\n' +
                '  - CLAUDE_ACCESS_TOKEN (for OAuth access token)\n\n' +
                'Get your API key from: https://console.anthropic.com/');
        }
        // Use OpenAI-compatible format for Anthropic API
        const { createOpenAIContentGenerator } = await import('./openaiContentGenerator/index.js');
        const anthropicConfig = {
            ...config,
            apiKey,
            baseUrl: 'https://api.anthropic.com/v1',
            model: config.model || 'claude-3-5-sonnet-20241022',
        };
        return createOpenAIContentGenerator(anthropicConfig, gcConfig);
    }
    throw new Error(`Error creating contentGenerator: Unsupported authType: ${config.authType}`);
}
//# sourceMappingURL=contentGenerator.js.map