import * as MediaLibrary from 'expo-media-library';
import { ExtendedAsset } from './types'; // Assuming ExtendedAsset is defined in types.ts

// Helper to fetch assets with pagination and EXIF info
const fetchAssetsWithExif = async (
    mediaType: MediaLibrary.MediaType[],
    createdAfter?: number,
    createdBefore?: number,
    descending: boolean = true // Default to descending
): Promise<ExtendedAsset[]> => {
    let allAssets: MediaLibrary.Asset[] = [];
    let hasNextPage = true;
    let after: string | undefined = undefined;

    while (hasNextPage) {
        const media = await MediaLibrary.getAssetsAsync({
            mediaType,
            first: 500, // Fetch in batches of 500
            sortBy: [MediaLibrary.SortBy.creationTime],
            createdAfter,
            createdBefore,
            after,
            descending,
        });

        allAssets = allAssets.concat(media.assets);
        hasNextPage = media.hasNextPage;
        after = media.endCursor;
    }

    // For each asset, get full EXIF information
    const assetsWithExif = await Promise.all(
        allAssets.map(async (asset) => {
            try {
                const assetInfo = await MediaLibrary.getAssetInfoAsync(asset.id);
                return {
                    ...asset,
                    exif: assetInfo.exif || null,
                    location: assetInfo.location || null
                };
            } catch (error) {
                console.warn(`Failed to get EXIF for asset ${asset.id}:`, error);
                return asset;
            }
        })
    );

    return assetsWithExif;
};

// 获取指定时间范围内的媒体文件（包含 EXIF 信息），并按日期倒序
export const getMediaByDateRange = async (startDate: Date, endDate: Date): Promise<ExtendedAsset[]> => {
    try {
        const { status } = await MediaLibrary.requestPermissionsAsync();
        if (status !== 'granted') {
            console.warn('Media library permission not granted');
            return [];
        }
        return await fetchAssetsWithExif(
            ['photo', 'video'],
            startDate.getTime(),
            endDate.getTime(),
            true // Always descending for this function
        );
    } catch (error) {
        console.error('Error in getMediaByDateRange:', error);
        return [];
    }
};

// 获取所有需要上传的媒体文件（从某个时间点之后，按日期倒序，包含 EXIF 信息）
export const getMediaForUpload = async (lastUploadTimestamp?: number): Promise<ExtendedAsset[]> => {
    try {
        const { status } = await MediaLibrary.requestPermissionsAsync();
        if (status !== 'granted') {
            console.warn('Media library permission not granted');
            return [];
        }
        return await fetchAssetsWithExif(
            ['photo', 'video'],
            lastUploadTimestamp, // Only fetch assets created after this timestamp
            undefined, // No end date
            true // Always descending
        );
    } catch (error) {
        console.error('Error in getMediaForUpload:', error);
        return [];
    }
};