// CORS proxy utilities for streaming audio/video content.
// The self-hosted proxy provides stream URLs, but actual segment downloads
// may still require CORS proxying for blob://, DASH, and HLS streams.

const PROXIES = [
    { url: 'http://your-nas-ip:8081/', param: 'url=' }, // Local proxy - change to your NAS IP
    { url: 'https://audio-proxy.binimum.org/proxy-audio', param: 'url=' },
    { url: 'https://corsproxy.io/?', param: '' },
    { url: 'https://api.allorigins.win/raw?url=', param: '' },
];

let proxyIndex = 0;
let failedProxies = new Set();

export const getProxyUrl = (url) => {
    if (!url || typeof url !== 'string') return url;
    if (window.__tidalOriginExtension) return url;
    if (url.startsWith('blob:')) return url;
    if (url.startsWith('https://audio-proxy.binimum.org/')) return url;

    // Find first working proxy
    for (let i = 0; i < PROXIES.length; i++) {
        const proxy = PROXIES[(proxyIndex + i) % PROXIES.length];
        if (!failedProxies.has(proxy.url)) {
            proxyIndex = (proxyIndex + i) % PROXIES.length;
            return `${proxy.url}${proxy.param}${encodeURIComponent(url)}`;
        }
    }

    // All proxies failed, reset and try first one
    failedProxies.clear();
    const proxy = PROXIES[0];
    return `${proxy.url}${proxy.param}${encodeURIComponent(url)}`;
};

export const markProxyFailed = (url) => {
    for (const proxy of PROXIES) {
        if (url.includes(proxy.url)) {
            failedProxies.add(proxy.url);
            console.warn(`Proxy ${proxy.url} marked as failed, rotating...`);
            rotateProxy();
            break;
        }
    }
};

export const rotateProxy = () => {
    proxyIndex = (proxyIndex + 1) % PROXIES.length;
};
