const CACHE_NAME = 'yangquan-wedding-v2';
const MAX_CACHE_ITEMS = 200;

// 只缓存静态资源，不缓存PHP动态页面和API
const STATIC_EXTENSIONS = /\.(css|js|png|jpg|jpeg|gif|webp|svg|ico|woff2?|ttf|eot|mp4|mp3|json)$/i;

const CACHE_URLS = [
    '/index.php',
    '/css/style.css',
    '/css/digital_human.css',
    '/js/main.js',
    '/js/ai.js',
    '/js/map.js',
    '/manifest.json'
];

self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME).then(cache => {
            return cache.addAll(CACHE_URLS).catch(err => {
                console.warn('SW precache部分失败:', err);
            });
        })
    );
    // 不立即激活，等旧SW释放后再激活
});

self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(keys => {
            return Promise.all(
                keys.filter(key => key !== CACHE_NAME).map(key => caches.delete(key))
            );
        }).then(() => {
            // 激活后接管所有客户端
            return self.clients.claim();
        })
    );
});

self.addEventListener('fetch', event => {
    // 只处理GET请求
    if (event.request.method !== 'GET') return;

    const url = new URL(event.request.url);

    // 跳过API请求和PHP动态页面
    if (url.pathname.startsWith('/api/') || url.pathname.endsWith('.php') && !url.pathname.endsWith('/index.php')) {
        return;
    }

    // 只缓存静态资源（同源）
    if (url.origin === location.origin && !STATIC_EXTENSIONS.test(url.pathname) && url.pathname !== '/index.php') {
        return;
    }

    event.respondWith(
        fetch(event.request).then(response => {
            if (response && response.status === 200) {
                // 只缓存静态资源类型
                const contentType = response.headers.get('Content-Type') || '';
                if (url.pathname === '/index.php' ||
                    STATIC_EXTENSIONS.test(url.pathname) ||
                    contentType.includes('image/') ||
                    contentType.includes('text/css') ||
                    contentType.includes('text/javascript') ||
                    contentType.includes('application/javascript') ||
                    contentType.includes('font/') ||
                    contentType.includes('video/') ||
                    contentType.includes('audio/')) {
                    
                    const responseClone = response.clone();
                    caches.open(CACHE_NAME).then(cache => {
                        // 限制缓存条目数量
                        cache.keys().then(keys => {
                            if (keys.length >= MAX_CACHE_ITEMS) {
                                cache.delete(keys[0]);
                            }
                        });
                        cache.put(event.request, responseClone);
                    });
                }
            }
            return response;
        }).catch(() => {
            return caches.match(event.request).then(response => {
                // 只对静态资源或index做离线回退
                if (response) return response;
                if (url.pathname === '/' || url.pathname === '/index.php') {
                    return caches.match('/index.php');
                }
                return new Response('离线状态下不可用', { status: 503 });
            });
        })
    );
});
