const CACHE_NAME = "shanhaijing-ai-v146";
const CACHE_PREFIX = "shanhaijing-ai-";
const ASSETS = [
  "./",
  "./index.html",
  "./styles.css?v=146",
  "./app.js?v=146",
  "./manifest.webmanifest",
  "./assets/shanhaijing-ai-icon.png",
];

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => cache.addAll(ASSETS)),
  );
  self.skipWaiting();
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    cleanOldCaches(),
  );
  self.clients.claim();
});

async function cleanOldCaches() {
  const keys = await caches.keys();
  return Promise.all(
    keys
      .filter((key) => (key.startsWith(CACHE_PREFIX) || key.startsWith("qingyan-xuetu-")) && key !== CACHE_NAME)
      .map((key) => caches.delete(key)),
  );
}

async function notifyClients(message) {
  const clients = await self.clients.matchAll({ type: "window" });
  clients.forEach((client) => client.postMessage(message));
}

self.addEventListener("message", (event) => {
  if (event.data?.type === "CLEAN_OLD_CACHES") {
    event.waitUntil(cleanOldCaches());
  }
});

self.addEventListener("fetch", (event) => {
  if (event.request.method !== "GET") return;
  event.respondWith(
    caches.match(event.request).then((cached) => (
      cached || fetch(event.request).then((response) => {
        const copy = response.clone();
        caches.open(CACHE_NAME)
          .then((cache) => cache.put(event.request, copy))
          .catch(() => cleanOldCaches().then(() => notifyClients({
            type: "CACHE_WRITE_FAILED",
            message: "离线缓存空间可能不足，已尝试清理早期缓存。",
          })));
        return response;
      }).catch(() => caches.match("./index.html"))
    )),
  );
});
