(function(){
    if(window.MXUsageTelemetry) return;
    const originalFetch = window.fetch.bind(window);
    const terminalTaskIds = new Set();
    const canvasTasks = new Map();
    async function report(event){
        try {
            await originalFetch('/api/usage/client-events', {
                method:'POST',
                credentials:'include',
                headers:{'Content-Type':'application/json'},
                body:JSON.stringify(event),
                keepalive:true
            });
        } catch (_) {
            // Diagnostics must never interrupt generation.
        }
    }

    function parsedBody(options){
        if(typeof options?.body !== 'string') return {};
        try { return JSON.parse(options.body); } catch (_) { return {}; }
    }

    function eventFromPayload(payload, status, error='', referenceId='', source='desktop'){
        return {
            category:'image',
            status,
            model:String(payload.model || payload.ms_model || payload.workflow_json || ''),
            provider:String(payload.provider_id || payload.provider || ''),
            prompt:String(payload.prompt || payload.message || ''),
            reference_id:String(referenceId || ''),
            error:String(error || ''),
            source
        };
    }

    window.MXUsageTelemetry = {report, eventFromPayload};

    window.fetch = async function(input, options){
        const method = String(options?.method || (input && input.method) || 'GET').toUpperCase();
        const rawUrl = typeof input === 'string' ? input : input?.url || '';
        const url = new URL(rawUrl, location.href);
        const localRequest = url.origin === location.origin;
        const path = url.pathname;
        const payload = parsedBody(options);
        let response;
        try {
            response = await originalFetch(input, options);
        } catch (error) {
            if(localRequest && method === 'POST' && ['/api/online-image','/api/generate','/api/ms/generate','/api/angle/generate'].includes(path)){
                report(eventFromPayload(payload, 'failed', error?.message || String(error), '', path));
            }
            throw error;
        }

        if(!localRequest) return response;
        if(method === 'POST' && path === '/api/canvas-image-tasks'){
            response.clone().json().then(data => {
                if(data?.task_id) canvasTasks.set(String(data.task_id), payload);
            }).catch(() => {});
            return response;
        }
        const taskMatch = method === 'GET' && path.match(/^\/api\/canvas-image-tasks\/([^/]+)$/);
        if(taskMatch){
            response.clone().json().then(data => {
                const taskId = decodeURIComponent(taskMatch[1]);
                if(!['succeeded','failed'].includes(data?.status) || terminalTaskIds.has(taskId)) return;
                terminalTaskIds.add(taskId);
                const taskPayload = canvasTasks.get(taskId) || {model:data?.model, provider_id:data?.provider_id};
                report(eventFromPayload(taskPayload, data.status, data.error || '', taskId, 'desktop-canvas'));
                canvasTasks.delete(taskId);
            }).catch(() => {});
            return response;
        }
        if(method === 'POST' && ['/api/online-image','/api/generate','/api/ms/generate','/api/angle/generate'].includes(path)){
            response.clone().text().then(text => {
                let data = {};
                try { data = JSON.parse(text); } catch (_) {}
                const status = response.ok ? (data.status === 'failed' ? 'failed' : 'succeeded') : 'failed';
                const error = response.ok ? (data.error || '') : (data.detail || data.error || text).slice(0, 1000);
                report(eventFromPayload(payload, status, error, data.task_id || data.id || '', path));
            }).catch(() => {});
        }
        return response;
    };
})();
