/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
import { OpenAIContentGenerator } from '../core/openaiContentGenerator.js';
import { SharedTokenManager } from './sharedTokenManager.js';
// Default fallback base URL if no endpoint is provided
const DEFAULT_QWEN_BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
/**
 * Qwen Content Generator that uses Qwen OAuth tokens with automatic refresh
 */
export class QwenContentGenerator extends OpenAIContentGenerator {
    qwenClient;
    sharedManager;
    currentToken;
    constructor(qwenClient, contentGeneratorConfig, config) {
        // Initialize with empty API key, we'll override it dynamically
        super(contentGeneratorConfig, config);
        this.qwenClient = qwenClient;
        this.sharedManager = SharedTokenManager.getInstance();
        // Set default base URL, will be updated dynamically
        this.client.baseURL = DEFAULT_QWEN_BASE_URL;
    }
    /**
     * Get the current endpoint URL with proper protocol and /v1 suffix
     */
    getCurrentEndpoint(resourceUrl) {
        const baseEndpoint = resourceUrl || DEFAULT_QWEN_BASE_URL;
        const suffix = '/v1';
        // Normalize the URL: add protocol if missing, ensure /v1 suffix
        const normalizedUrl = baseEndpoint.startsWith('http')
            ? baseEndpoint
            : `https://${baseEndpoint}`;
        return normalizedUrl.endsWith(suffix)
            ? normalizedUrl
            : `${normalizedUrl}${suffix}`;
    }
    /**
     * Override error logging behavior to suppress auth errors during token refresh
     */
    shouldSuppressErrorLogging(error, _request) {
        // Suppress logging for authentication errors that we handle with token refresh
        return this.isAuthError(error);
    }
    /**
     * Get valid token and endpoint using the shared token manager
     */
    async getValidToken() {
        try {
            // Use SharedTokenManager for consistent token/endpoint pairing and automatic refresh
            const credentials = await this.sharedManager.getValidCredentials(this.qwenClient);
            if (!credentials.access_token) {
                throw new Error('No access token available');
            }
            return {
                token: credentials.access_token,
                endpoint: this.getCurrentEndpoint(credentials.resource_url),
            };
        }
        catch (error) {
            // Propagate auth errors as-is for retry logic
            if (this.isAuthError(error)) {
                throw error;
            }
            console.warn('Failed to get token from shared manager:', error);
            throw new Error('Failed to obtain valid Qwen access token. Please re-authenticate.');
        }
    }
    /**
     * Execute an operation with automatic credential management and retry logic.
     * This method handles:
     * - Dynamic token and endpoint retrieval
     * - Temporary client configuration updates
     * - Automatic restoration of original configuration
     * - Retry logic on authentication errors with token refresh
     *
     * @param operation - The operation to execute with updated client configuration
     * @param restoreOnCompletion - Whether to restore original config after operation completes
     * @returns The result of the operation
     */
    async executeWithCredentialManagement(operation, restoreOnCompletion = true) {
        // Attempt the operation with credential management and retry logic
        const attemptOperation = async () => {
            const { token, endpoint } = await this.getValidToken();
            // Store original configuration
            const originalApiKey = this.client.apiKey;
            const originalBaseURL = this.client.baseURL;
            // Apply dynamic configuration
            this.client.apiKey = token;
            this.client.baseURL = endpoint;
            try {
                const result = await operation();
                // For streaming operations, we may need to keep the configuration active
                if (restoreOnCompletion) {
                    this.client.apiKey = originalApiKey;
                    this.client.baseURL = originalBaseURL;
                }
                return result;
            }
            catch (error) {
                // Always restore on error
                this.client.apiKey = originalApiKey;
                this.client.baseURL = originalBaseURL;
                throw error;
            }
        };
        // Execute with retry logic for auth errors
        try {
            return await attemptOperation();
        }
        catch (error) {
            if (this.isAuthError(error)) {
                try {
                    // Use SharedTokenManager to properly refresh and persist the token
                    // This ensures the refreshed token is saved to oauth_creds.json
                    await this.sharedManager.getValidCredentials(this.qwenClient, true);
                    // Retry the operation once with fresh credentials
                    return await attemptOperation();
                }
                catch (_refreshError) {
                    throw new Error('Failed to obtain valid Qwen access token. Please re-authenticate.');
                }
            }
            throw error;
        }
    }
    /**
     * Override to use dynamic token and endpoint with automatic retry
     */
    async generateContent(request, userPromptId) {
        return this.executeWithCredentialManagement(() => super.generateContent(request, userPromptId));
    }
    /**
     * Override to use dynamic token and endpoint with automatic retry.
     * Note: For streaming, the client configuration is not restored immediately
     * since the generator may continue to be used after this method returns.
     */
    async generateContentStream(request, userPromptId) {
        return this.executeWithCredentialManagement(() => super.generateContentStream(request, userPromptId), false);
    }
    /**
     * Override to use dynamic token and endpoint with automatic retry
     */
    async countTokens(request) {
        return this.executeWithCredentialManagement(() => super.countTokens(request));
    }
    /**
     * Override to use dynamic token and endpoint with automatic retry
     */
    async embedContent(request) {
        return this.executeWithCredentialManagement(() => super.embedContent(request));
    }
    /**
     * Check if an error is related to authentication/authorization
     */
    isAuthError(error) {
        if (!error)
            return false;
        const errorMessage = error instanceof Error
            ? error.message.toLowerCase()
            : String(error).toLowerCase();
        // Define a type for errors that might have status or code properties
        const errorWithCode = error;
        const errorCode = errorWithCode?.status || errorWithCode?.code;
        return (errorCode === 401 ||
            errorCode === 403 ||
            errorCode === '401' ||
            errorCode === '403' ||
            errorMessage.includes('unauthorized') ||
            errorMessage.includes('forbidden') ||
            errorMessage.includes('invalid api key') ||
            errorMessage.includes('invalid access token') ||
            errorMessage.includes('token expired') ||
            errorMessage.includes('authentication') ||
            errorMessage.includes('access denied') ||
            (errorMessage.includes('token') && errorMessage.includes('expired')));
    }
    /**
     * Get the current cached token (may be expired)
     */
    getCurrentToken() {
        // First check internal state for backwards compatibility with tests
        if (this.currentToken) {
            return this.currentToken;
        }
        // Fall back to SharedTokenManager
        const credentials = this.sharedManager.getCurrentCredentials();
        return credentials?.access_token || null;
    }
    /**
     * Clear the cached token
     */
    clearToken() {
        // Clear internal state for backwards compatibility with tests
        this.currentToken = undefined;
        // Also clear SharedTokenManager
        this.sharedManager.clearCache();
    }
}
//# sourceMappingURL=qwenContentGenerator.js.map