
import { DefaultService } from '@/lib/api';

export const urlToBase64 = async (url: string): Promise<string> => {
    const fetchAndConvert = async (fetchUrl: string): Promise<string | null> => {
        try {
            const response = await fetch(fetchUrl, { mode: 'cors' });
            if (!response.ok) return null;
            const blob = await response.blob();
            return new Promise<string>((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = (e) => resolve(reader.result as string);
                reader.onerror = reject;
                reader.readAsDataURL(blob);
            });
        } catch (e) {
            return null;
        }
    };

    // First try: Direct fetch
    let result = await fetchAndConvert(url);
    if (result) return result;

    // If direct fetch fails, try signing the URL
    try {
        const response = await DefaultService.signUrlEndpoint({ url });
        const signedUrl = (response as any).data?.url;
        if (signedUrl && signedUrl !== url) {
             result = await fetchAndConvert(signedUrl);
             if (result) return result;
        }
    } catch (signError) {
        console.warn("Failed to sign URL", signError);
    }

    return ""; // Fallback for mediaUtils is usually empty string or handle externally
};

export const extractLastFrame = (videoSrc: string): Promise<string> => {
    return new Promise((resolve, reject) => {
        const video = document.createElement('video');
        video.crossOrigin = "anonymous"; 
        video.src = videoSrc;
        video.muted = true;
        video.onloadedmetadata = () => { video.currentTime = Math.max(0, video.duration - 0.1); };
        video.onseeked = () => {
            try {
                const canvas = document.createElement('canvas');
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                const ctx = canvas.getContext('2d');
                if (ctx) {
                    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                    resolve(canvas.toDataURL('image/png'));
                } else {
                    reject(new Error("Canvas context failed"));
                }
            } catch (e) { reject(e); } finally { video.remove(); }
        };
        video.onerror = () => { reject(new Error("Video load failed for frame extraction")); video.remove(); };
    });
};

export interface CropRect {
    x: number;
    y: number;
    width: number;
    height: number;
}

export const cropImage = (image: HTMLImageElement, crop: CropRect): string => {
    const canvas = document.createElement('canvas');
    const sx = image.naturalWidth / image.width;
    const sy = image.naturalHeight / image.height;

    // Ensure canvas dimensions are valid (non-zero and positive)
    canvas.width = Math.max(1, Math.floor(crop.width * sx));
    canvas.height = Math.max(1, Math.floor(crop.height * sy));

    const ctx = canvas.getContext('2d');
    if (!ctx) {
        throw new Error('Failed to get canvas context');
    }

    ctx.drawImage(
        image,
        crop.x * sx,
        crop.y * sy,
        crop.width * sx,
        crop.height * sy,
        0,
        0,
        canvas.width,
        canvas.height
    );

    return canvas.toDataURL('image/png');
};
