// Ormur PWA service worker — makes the served terminal UI an installable desktop/mobile app.
// Network-FIRST (the terminal must always reach the live agent); cache is only a fallback so the
// app shell loads offline. The live WS/SSE/API paths are never intercepted.
const CACHE = 'ormur-v1';
const SHELL = ['/', '/app.css', '/app.js', '/manifest.webmanifest', '/ormur.png'];

self.addEventListener('install', (e) => {
  // add each asset independently (NOT addAll, which is atomic — one 404 would reject the whole SW
  // install and leave the app uninstallable). Missing assets are skipped; runtime caching backfills.
  e.waitUntil(
    caches.open(CACHE)
      .then((c) => Promise.all(SHELL.map((u) => c.add(u).catch(() => {}))))
      .then(() => self.skipWaiting())
  );
});

self.addEventListener('activate', (e) => {
  e.waitUntil(
    caches.keys()
      .then((ks) => Promise.all(ks.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
      .then(() => self.clients.claim())
  );
});

self.addEventListener('fetch', (e) => {
  const u = new URL(e.request.url);
  // never touch the live terminal transport or any non-GET (let it hit the network untouched).
  if (e.request.method !== 'GET' || u.pathname.startsWith('/api') ||
      u.pathname.startsWith('/ws') || u.pathname.startsWith('/attach')) {
    return;
  }
  e.respondWith(
    fetch(e.request)
      .then((r) => {
        if (r.ok && u.origin === self.location.origin) {
          const copy = r.clone();
          caches.open(CACHE).then((c) => c.put(e.request, copy)).catch(() => {});
        }
        return r;
      })
      .catch(() => caches.match(e.request).then((r) => r || caches.match('/')))
  );
});
