const CacheManager = (function () {
    const CACHE_NAME = 'game-cache-v2';
    const DEBUG = false;

    function log(...args) {
        if (DEBUG) {
            console.log('[CacheManager]', ...args);
        }
    }

    const CACHE_PATTERNS = [
        /assets\/.*?\.png$/i,  // assets 目录及其子目录下的所有 PNG 文件
        /assets\/.*?\.jpg$/i,  // assets 目录及其子目录下的所有 JPG 文件
        /assets\/.*?\.jpeg$/i, // assets 目录及其子目录下的所有 JPEG 文件
        /assets\/.*?\.json$/i, // assets 目录及其子目录下的所有 JSON 文件
        /assets\/.*?\.mp3$/i,  // assets 目录及其子目录下的所有 MP3 文件
        /assets\/.*?\.wav$/i,  // assets 目录及其子目录下的所有 WAV 文件
    ];

    // 添加调试日志
    function shouldCacheRequest(url) {
        const shouldCache = CACHE_PATTERNS.some(pattern => {
            const matches = url.match(pattern);            
            return matches;
        });
        

        return shouldCache;
    }

    // 处理安装事件
    function handleInstall(event) {
        log('Service Worker installing...');
        // 跳过等待，直接激活
        self.skipWaiting();
        
        event.waitUntil(
            caches.open(CACHE_NAME).then(cache => {
                log('Cache opened');
            })
        );
    }

    // 处理请求
    async function handleFetch(event) {
        const request = event.request;

        if (request.method !== 'GET' || !shouldCacheRequest(request.url)) {
            return;
        }

        event.respondWith(
            (async () => {
                try {
                    // 先尝试从缓存获取
                    const cachedResponse = await caches.match(request);
                    if (cachedResponse) {
                        log('Cache hit:', request.url);
                        return cachedResponse;
                    }

                    log('Cache miss:', request.url);
                    // 从网络获取
                    const networkResponse = await fetch(request);
                    if (!networkResponse || networkResponse.status !== 200) {
                        return networkResponse;
                    }

                    // 缓存响应
                    const responseToCache = networkResponse.clone();
                    const cache = await caches.open(CACHE_NAME);
                    await cache.put(request, responseToCache);
                    log('Cached:', request.url);

                    return networkResponse;
                } catch (error) {
                    log('Fetch error:', error);
                    throw error;
                }
            })()
        );
    }

    // 处理激活事件
    function handleActivate(event) {
        log('Service Worker activating...');
        event.waitUntil(
            Promise.all([
                // 清理旧缓存
                caches.keys().then(cacheNames => {
                    return Promise.all(
                        cacheNames.map(cacheName => {
                            if (cacheName !== CACHE_NAME) {
                                log('Deleting old cache:', cacheName);
                                return caches.delete(cacheName);
                            }
                        })
                    );
                }),
                // 立即接管页面
                clients.claim()
            ])
        );
    }

    // 初始化
    function init() {
        self.addEventListener('install', handleInstall);
        self.addEventListener('fetch', handleFetch);
        self.addEventListener('activate', handleActivate);
    }

    return {
        init: init
    };
})();

// 初始化缓存管理器
CacheManager.init();