// API Base configuration
const API_BASE = '/api';

// Cache for providers info
let searchResultsCache = {};

/**
 * Get providers information
 */
async function getProvidersInfo() {
    if (!searchResultsCache.providers) {
        const response = await fetch(`${API_BASE}/providers`);
        searchResultsCache.providers = await response.json();
    }
    return searchResultsCache.providers;
}

/**
 * Check if a provider supports seasons (helper function)
 * @param {string} providerId - The provider ID (e.g., 'animesama')
 * @param {string} url - Optional URL to check for provider support
 * @returns {Promise<boolean>} - True if provider supports seasons
 */
async function providerSupportsSeasons(providerId, url = null) {
    try {
        const providers = await getProvidersInfo();

        // Check if provider ID exists in anime_providers
        if (providers.anime_providers && providers.anime_providers[providerId]) {
            const provider = providers.anime_providers[providerId];
            // Check if provider has explicit supports_seasons flag
            if (typeof provider.supports_seasons === 'boolean') {
                return provider.supports_seasons;
            }
            // Otherwise, check by provider ID (known season-supporting providers)
            return ['anime-sama', 'anime-ultime', 'french-manga'].includes(providerId);
        }

        // Fallback: check URL if provided
        if (url) {
            const lowerUrl = url.toLowerCase();
            // Check all anime provider domains
            for (const [pid, provider] of Object.entries(providers.anime_providers || {})) {
                if (provider.domains) {
                    for (const domain of provider.domains) {
                        if (lowerUrl.includes(domain.toLowerCase())) {
                            // Re-check with detected provider ID
                            return providerSupportsSeasons(pid);
                        }
                    }
                }
            }
        }

        return false;
    } catch (error) {
        console.error('Error checking provider season support:', error);
        return false;
    }
}

/**
 * Search anime across all providers
 */
async function searchAnime(query, lang, includeMetadata) {
    if (!query) {
        throw new Error('Veuillez entrer un nom d\'anime');
    }

    const response = await fetch(
        `${API_BASE}/anime/search?q=${encodeURIComponent(query)}&lang=${lang}&include_metadata=${includeMetadata}`
    );

    if (!response.ok) {
        throw new Error('Erreur lors de la recherche');
    }

    return await response.json();
}

/**
 * Load episodes for an anime
 */
async function loadEpisodes(animeUrl, lang) {
    const response = await fetch(
        `${API_BASE}/anime/episodes?url=${encodeURIComponent(animeUrl)}&lang=${lang}`
    );

    if (!response.ok) {
        throw new Error('Erreur lors du chargement des épisodes');
    }

    return await response.json();
}

/**
 * Download an anime episode
 */
async function downloadEpisode(episodeUrl) {
    const response = await fetch(`${API_BASE}/anime/download?url=${encodeURIComponent(episodeUrl)}`, {
        method: 'POST'
    });

    if (!response.ok) {
        throw new Error('Erreur lors du démarrage du téléchargement');
    }

    return await response.json();
}

/**
 * Download entire season
 */
async function downloadSeason(animeUrl, lang) {
    const response = await fetch(
        `${API_BASE}/anime/download-season?url=${encodeURIComponent(animeUrl)}&lang=${lang}`,
        { method: 'POST' }
    );

    if (!response.ok) {
        const error = await response.json();
        throw new Error(error.detail || 'Impossible de démarrer le téléchargement de la saison');
    }

    return await response.json();
}

/**
 * Start a direct download
 */
async function startDownload(url) {
    const response = await fetch(`${API_BASE}/download`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url })
    });

    if (!response.ok) {
        throw new Error('Erreur lors du démarrage du téléchargement');
    }

    return await response.json();
}

/**
 * Get all downloads
 */
async function getDownloads() {
    const response = await fetch(`${API_BASE}/downloads`);

    if (!response.ok) {
        throw new Error('Erreur lors du chargement des téléchargements');
    }

    return await response.json();
}

/**
 * Pause a download
 */
async function pauseDownload(id) {
    const response = await fetch(`${API_BASE}/download/${id}/pause`, { method: 'POST' });

    if (!response.ok) {
        throw new Error('Erreur lors de la mise en pause');
    }

    return await response.json();
}

/**
 * Resume a download
 */
async function resumeDownload(id) {
    const response = await fetch(`${API_BASE}/download/${id}/resume`, { method: 'POST' });

    if (!response.ok) {
        throw new Error('Erreur lors de la reprise');
    }

    return await response.json();
}

/**
 * Cancel/delete a download
 */
async function cancelDownload(id) {
    const response = await fetch(`${API_BASE}/download/${id}`, { method: 'DELETE' });

    if (!response.ok) {
        throw new Error('Erreur lors de la suppression');
    }

    return await response.json();
}

// Make functions available globally
window.getProvidersInfo = getProvidersInfo;
window.providerSupportsSeasons = providerSupportsSeasons;
window.searchAnime = searchAnime;
window.loadEpisodes = loadEpisodes;
window.downloadEpisode = downloadEpisode;
window.downloadSeason = downloadSeason;
window.startDownload = startDownload;
window.getDownloads = getDownloads;
window.pauseDownload = pauseDownload;
window.resumeDownload = resumeDownload;
window.cancelDownload = cancelDownload;
