"use strict";

const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");

const root = path.join(__dirname, "..");
const html = fs.readFileSync(path.join(root, "index.html"), "utf8");
const styles = fs.readFileSync(path.join(root, "styles.css"), "utf8");
const robots = fs.readFileSync(path.join(root, "robots.txt"), "utf8");
const llms = fs.readFileSync(path.join(root, "llms.txt"), "utf8");
const installer = fs.readFileSync(path.join(root, "install-lite-front-door.py"), "utf8");

test("front door keeps the legally required ICP link", () => {
  assert.match(html, /陕ICP备2025071211号-1/);
  assert.match(html, /https:\/\/beian\.miit\.gov\.cn\//);
});

test("front door makes the new code channel the primary route", () => {
  assert.match(html, /href="\/code\/"/);
  assert.match(html, /光湖代码频道/);
  assert.match(llms, /https:\/\/guanghulab\.com\/code\/bingshuo\/fifth-domain/);
  assert.match(robots, /Allow: \/code\//);
});

test("front door preserves the legacy Fifth Domain as history", () => {
  assert.match(html, /href="\/fifth-domain\/bingshuo\/fifth-domain"/);
  assert.match(html, /第五域历史事实源/);
  assert.match(llms, /Legacy Fifth Domain history/);
  assert.match(html, /href="https:\/\/guanghubingshuo\.com\/code\/"/);
});

test("AI discovery and search remain on the domestic domain", () => {
  assert.match(html, /href="\/api\/ai\/"/);
  assert.match(html, /href="\/api\/ai\/v1\/search\?q=/);
  assert.match(html, /SearchAction/);
  assert.match(html, /\.well-known\/guanghu\.json/);
  assert.match(llms, /HLCC-ICE-000001/);
});

test("page is a script-free lightweight static surface", () => {
  const executableScripts = [...html.matchAll(/<script(?![^>]*type="application\/ld\+json")[^>]*>/g)];
  assert.equal(executableScripts.length, 0);
  assert.doesNotMatch(html, /<img|<svg|<video|<canvas|iframe/i);
  assert.doesNotMatch(styles, /linear-gradient|radial-gradient|animation:|backdrop-filter/i);
  assert.ok(Buffer.byteLength(html) + Buffer.byteLength(styles) < 16000);
});

test("public page never embeds infrastructure addresses or credentials", () => {
  assert.doesNotMatch(html, /(?:\d{1,3}\.){3}\d{1,3}/);
  assert.doesNotMatch(html, /zy_gtw_/);
  assert.doesNotMatch(html, /password|private[_ -]?key|token/i);
});

test("front door remains responsive", () => {
  assert.match(styles, /@media\s*\(max-width:\s*640px\)/);
  assert.match(styles, /clamp\(/);
});

test("installer changes only the code route with backup and rollback", () => {
  assert.match(installer, /\/var\/backups\/guanghu\/front-door/);
  assert.match(installer, /proxy_pass http:\/\/127\.0\.0\.1:18088\/code\//);
  assert.match(installer, /nginx", "-t"/);
  assert.match(installer, /systemctl", "reload", "nginx"/);
  assert.match(installer, /legacy Fifth Domain verification failed/);
  assert.match(installer, /shutil\.copy2\(backup_root/);
});
