/**
 * src/lib/youtubeApi.ts
 * YouTube Data API v3 key rotator.
 *
 * Reads up to 4 keys from env:
 *   YOUTUBE_API_KEY, YOUTUBE_API_KEY_2, YOUTUBE_API_KEY_3, YOUTUBE_API_KEY_4
 *
 * On each call, tries the primary key. If it gets a 403 (quota exceeded /
 * forbidden) or 429 (rate limit), it rotates to the next key and retries.
 * If ALL keys fail, throws the last error so the caller can surface it.
 *
 * Usage:
 *   import { ytGet } from '@/lib/youtubeApi';
 *   const data = await ytGet('/videos', { chart: 'mostPopular', part: 'snippet', maxResults: 50 });
 */

import axios, { AxiosError } from 'axios';

const BASE = 'https://www.googleapis.com/youtube/v3';

/** Returns the ordered list of configured API keys (filters out empties). */
function getKeys(): string[] {
    return [
        process.env.YOUTUBE_API_KEY,
        process.env.YOUTUBE_API_KEY_2,
        process.env.YOUTUBE_API_KEY_3,
        process.env.YOUTUBE_API_KEY_4,
    ].filter((k): k is string => typeof k === 'string' && k.trim().length > 0);
}

let _currentKeyIndex = 0;

/**
 * Makes a GET request to the YouTube Data API, rotating keys on 403/429.
 * @param path  e.g. '/videos', '/channels', '/search'
 * @param params  Query params (without `key` — the rotator adds it)
 */
export async function ytGet(path: string, params: Record<string, string | number | undefined>): Promise<any> {
    const keys = getKeys();
    if (keys.length === 0) throw new Error('No YOUTUBE_API_KEY configured in .env');

    // Try each key, starting from the last-known working one
    let lastError: unknown;
    for (let attempt = 0; attempt < keys.length; attempt++) {
        const keyIndex = (_currentKeyIndex + attempt) % keys.length;
        const key = keys[keyIndex];
        try {
            const res = await axios.get(`${BASE}${path}`, { params: { ...params, key } });
            // Key worked — remember it for next time
            _currentKeyIndex = keyIndex;
            return res.data;
        } catch (err) {
            const status = (err as AxiosError)?.response?.status;
            const isQuotaError = status === 403 || status === 429;
            if (isQuotaError) {
                const nextIdx = (keyIndex + 1) % keys.length;
                console.warn(
                    `[YouTube] Key ${keyIndex + 1} hit ${status}. Rotating to key ${nextIdx + 1} of ${keys.length}.`
                );
                lastError = err;
                // Rotate index forward so the next request starts from the good key
                _currentKeyIndex = nextIdx;
                continue; // try next key
            }
            // Non-quota error (400 bad request, network, etc.) — surface immediately
            throw err;
        }
    }
    // All keys exhausted
    const quotaMsg = keys.length > 1
        ? `All ${keys.length} YouTube API keys have hit their quota limit. Add more keys or wait for reset at midnight Pacific Time.`
        : 'YouTube API key quota exceeded. Add YOUTUBE_API_KEY_2/3/4 in .env for automatic rotation.';
    const wrappedError = new Error(quotaMsg);
    (wrappedError as any).originalError = lastError;
    (wrappedError as any).quotaExhausted = true;
    throw wrappedError;
}

/** Convenience: returns the count of configured keys for status display. */
export function getKeyCount(): number {
    return getKeys().length;
}
