import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";

const pwaRoot = dirname(dirname(fileURLToPath(import.meta.url)));

function readPwaFile(...parts) {
  return readFileSync(join(pwaRoot, ...parts), "utf8");
}

test("index links the install manifest and app icons", () => {
  const html = readPwaFile("index.html");

  assert.match(html, /<link rel="manifest" href="\/manifest\.webmanifest">/);
  assert.match(html, /<meta name="theme-color" content="#15171b">/);
  assert.match(html, /<link rel="icon" type="image\/png" href="\/icons\/icon-192\.png\?v=8">/);
  assert.match(html, /<link rel="apple-touch-icon" href="\/icons\/icon-192\.png\?v=8">/);
});

test("web app manifest exposes installable mobile metadata", () => {
  const manifest = JSON.parse(readPwaFile("public", "manifest.webmanifest"));

  assert.equal(manifest.name, "Code Remote Manager");
  assert.equal(manifest.short_name, "Codex");
  assert.equal(manifest.start_url, "/");
  assert.equal(manifest.scope, "/");
  assert.equal(manifest.display, "standalone");
  assert.equal(manifest.theme_color, "#15171b");
  assert.equal(manifest.background_color, "#15171b");
  assert.deepEqual(
    manifest.icons.map(({ src, sizes, type, purpose }) => ({ src, sizes, type, purpose })),
    [
      { src: "/icons/icon-192.png?v=8", sizes: "192x192", type: "image/png", purpose: "any maskable" },
      { src: "/icons/icon-512.png?v=8", sizes: "512x512", type: "image/png", purpose: "any maskable" }
    ]
  );
});

test("app registers the root service worker", () => {
  const app = readPwaFile("src", "App.jsx");
  const serviceWorker = readPwaFile("public", "sw.js");

  assert.match(app, /navigator\.serviceWorker\.register\("\/sw\.js"\)/);
  assert.match(serviceWorker, /code-remote-manager-shell-v3/);
  assert.match(serviceWorker, /self\.addEventListener\("install"/);
  assert.match(serviceWorker, /self\.addEventListener\("fetch"/);
});

test("PWA icon consumers use the current cache-busted icon URLs", () => {
  const html = readPwaFile("index.html");
  const manifest = JSON.parse(readPwaFile("public", "manifest.webmanifest"));
  const notifications = readPwaFile("src", "features", "notifications", "system-notification.js");
  const serviceWorker = readPwaFile("public", "sw.js");

  assert.match(html, /href="\/icons\/icon-192\.png\?v=8"/);
  assert.deepEqual(manifest.icons.map(({ src }) => src), [
    "/icons/icon-192.png?v=8",
    "/icons/icon-512.png?v=8"
  ]);
  assert.match(notifications, /icon: "\/icons\/icon-192\.png\?v=8"/);
  assert.match(serviceWorker, /code-remote-manager-shell-v3/);
});
