import { readFile } from 'node:fs/promises'
import { resolve } from 'node:path'

const root = resolve(new URL('..', import.meta.url).pathname)
const manifest = JSON.parse(await readFile(resolve(root, 'public/manifest.webmanifest'), 'utf8'))
const serviceWorker = await readFile(resolve(root, 'public/sw.js'), 'utf8')
const main = await readFile(resolve(root, 'src/main.tsx'), 'utf8')
const fail = (message) => { throw new Error(`PWA asset check: ${message}`) }

if (manifest.name !== 'BitBybit CAD Studio' || manifest.start_url !== '/start' || manifest.scope !== '/' || manifest.display !== 'standalone' || manifest.theme_color !== '#111519') fail('manifest metadata is invalid.')
if (!serviceWorker.includes("const CACHE_NAME = 'bitbybit-cad-shell-v1'") || !serviceWorker.includes('skipWaiting') || !serviceWorker.includes('clients.claim') || !serviceWorker.includes('caches.match') || !serviceWorker.includes('keys.filter((key) => key !== CACHE_NAME)') || !serviceWorker.includes('caches.delete(key)')) fail('service worker install/activate/fallback/migration policy is incomplete.')
if (!main.includes("navigator.serviceWorker.register('/sw.js'")) fail('production service worker registration is missing.')

console.log(JSON.stringify({ status: 'pwa-assets-pass', name: manifest.name, startUrl: manifest.start_url, cache: 'bitbybit-cad-shell-v1' }, null, 2))
