/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { useState, useEffect, useCallback } from 'react';
import { AuthType, loadApiKey, debugLogger, SixthAuthFlow, } from '@google/gemini-cli-core';
import { getErrorMessage } from '@google/gemini-cli-core';
import { AuthState } from '../types.js';
import { validateAuthMethod } from '../../config/auth.js';
export function validateAuthMethodWithSettings(authType, settings) {
    const enforcedType = settings.merged.security?.auth?.enforcedType;
    if (enforcedType && enforcedType !== authType) {
        return `Authentication is enforced to be ${enforcedType}, but you are currently using ${authType}.`;
    }
    if (settings.merged.security?.auth?.useExternal) {
        return null;
    }
    // If using Gemini API key, we don't validate it here as we might need to prompt for it.
    if (authType === AuthType.USE_GEMINI) {
        return null;
    }
    return validateAuthMethod(authType);
}
export const useAuthCommand = (settings, config) => {
    const [authState, setAuthState] = useState(AuthState.Unauthenticated);
    const [authError, setAuthError] = useState(null);
    const [apiKeyDefaultValue, setApiKeyDefaultValue] = useState(undefined);
    const onAuthError = useCallback((error) => {
        setAuthError(error);
        if (error) {
            setAuthState(AuthState.Unauthenticated);
        }
    }, [setAuthError, setAuthState]);
    const reloadApiKey = useCallback(async () => {
        const storedKey = (await loadApiKey()) ?? '';
        const envKey = process.env['GEMINI_API_KEY'] ?? '';
        const key = storedKey || envKey;
        setApiKeyDefaultValue(key);
        return key; // Return the key for immediate use
    }, []);
    useEffect(() => {
        (async () => {
            if (authState !== AuthState.Unauthenticated) {
                return;
            }
            // First, check if user is authenticated with Sixth
            const sixthAuth = new SixthAuthFlow();
            const isUserAuthenticated = await sixthAuth.isUserAuthenticated();
            if (!isUserAuthenticated) {
                // User needs Sixth authentication
                setAuthState(AuthState.SixthAuthRequired);
                return;
            }
            // User is authenticated with Sixth, proceed with Gemini API auth
            const authType = AuthType.USE_GEMINI;
            // Load the hardcoded key (no need to check since it's always available)
            await reloadApiKey();
            try {
                await config.refreshAuth(authType);
                debugLogger.log(`Authenticated via "${authType}" (hardcoded).`);
                setAuthError(null);
                setAuthState(AuthState.Authenticated);
            }
            catch (e) {
                onAuthError(`Failed to login. Message: ${getErrorMessage(e)}`);
            }
        })();
    }, [
        settings,
        config,
        authState,
        setAuthState,
        setAuthError,
        onAuthError,
        reloadApiKey,
    ]);
    return {
        authState,
        setAuthState,
        authError,
        onAuthError,
        apiKeyDefaultValue,
        reloadApiKey,
    };
};
//# sourceMappingURL=useAuth.js.map