// Fictional, dependency-free local example. Run with Node 24: node example.mjs
// The extractor understands only this fixture's HTML and inline JSON-LD shape.
import assert from 'node:assert/strict';
import { createServer } from 'node:http';

const url = 'https://harbordesk.example/apps/export';
const appId = `${url}#app`;
const body = '<main><h1>HarborDesk Export</h1><p>Desktop CSV export utility for Windows and macOS.</p><p>One-time license: <span id="amount">39.00</span> <span id="currency">USD</span>.</p></main>';
const organization = { '@context': 'https://schema.org', '@type': 'Organization', '@id': 'https://harbordesk.example/#org', name: 'HarborDesk', url: 'https://harbordesk.example/' };
const app = price => ({ '@context': 'https://schema.org', '@type': 'SoftwareApplication', '@id': appId, name: 'HarborDesk Export', url, applicationCategory: 'BusinessApplication', operatingSystem: 'Windows, macOS', offers: { '@type': 'Offer', price, priceCurrency: 'USD' } });
const script = (id, value) => `<script id="${id}" type="application/ld+json">${JSON.stringify(value)}</script>`;
function html(mode) {
  const core = app(mode === 'before' ? '29.00' : '39.00');
  // Deliberately unsupported sample rating, removed in the corrected state.
  const stalePlugin = { ...app('19.00'), aggregateRating: { '@type': 'AggregateRating', ratingValue: 4.9, ratingCount: 212 } };
  return `<!doctype html><html lang="en"><head><title>HarborDesk Export</title><link rel="canonical" href="${url}">${script('app-template', core)}${mode === 'before' ? script('stale-plugin', stalePlugin) : ''}${script('site-identity', organization)}</head><body>${body}<footer>HarborDesk</footer></body></html>`;
}
function inspect(document) {
  const main = document.match(/<main>[\s\S]*?<\/main>/)?.[0] ?? '';
  const amount = main.match(/id="amount">([^<]+)</)?.[1];
  const currency = main.match(/id="currency">([^<]+)</)?.[1];
  assert.ok(amount && currency, 'Fixture visible price is missing');
  const records = [...document.matchAll(/<script id="([^"]+)" type="application\/ld\+json">([\s\S]*?)<\/script>/g)].map(([, emitter, text]) => ({ emitter, value: JSON.parse(text) }));
  const apps = records.filter(({ value }) => value['@id'] === appId);
  const prices = apps.map(({ emitter, value }) => ({ emitter, price: value.offers.price, currency: value.offers.priceCurrency }));
  const mismatches = prices.filter(value => value.price !== amount || value.currency !== currency);
  const unsupportedRatings = apps.filter(({ value }) => 'aggregateRating' in value).map(value => value.emitter);
  return {
    visiblePrice: `${amount} ${currency}`, appRecords: apps.length, prices,
    priceMismatches: mismatches.map(value => value.emitter),
    conflictingPrices: new Set(prices.map(value => `${value.price} ${value.currency}`)).size > 1,
    unsupportedRatings,
    organization: records.find(({ value }) => value['@id'] === organization['@id'])?.value,
  };
}
let mode = 'before';
const server = createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  const path = new URL(req.url, 'http://localhost').pathname;
  if (path !== '/apps/export') {
    res.statusCode = path === '/workspace' ? 401 : 404;
    res.setHeader('X-Robots-Tag', 'noindex');
    return res.end(path === '/workspace' ? 'Sign in required' : 'Not found');
  }
  res.end(html(mode));
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const origin = `http://127.0.0.1:${server.address().port}`;
const read = async (path, agent = 'schema-example') => {
  const response = await fetch(origin + path, { headers: { 'User-Agent': agent } });
  return { status: response.status, robots: response.headers.get('x-robots-tag'), html: await response.text() };
};
try {
  const before = await read('/apps/export');
  const beforeResult = inspect(before.html);
  assert.equal(before.status, 200);
  assert.deepEqual(beforeResult.priceMismatches, ['app-template', 'stale-plugin']);
  assert.equal(beforeResult.conflictingPrices, true);
  assert.deepEqual(beforeResult.unsupportedRatings, ['stale-plugin']);
  const excludedBefore = await read('/workspace');
  const missingBefore = await read('/missing');
  mode = 'after';
  const after = await read('/apps/export');
  const afterResult = inspect(after.html);
  assert.equal(after.status, 200);
  assert.equal(after.robots, null);
  assert.equal(afterResult.appRecords, 1);
  assert.deepEqual(afterResult.priceMismatches, []);
  assert.equal(afterResult.conflictingPrices, false);
  assert.deepEqual(afterResult.unsupportedRatings, []);
  assert.deepEqual(afterResult.organization, beforeResult.organization);
  assert.equal(after.html.match(/<main>[\s\S]*?<\/main>/)[0], body);
  assert.equal(before.html.match(/<main>[\s\S]*?<\/main>/)[0], body);
  const canonical = document => document.match(/<link rel="canonical"[^>]+>/)[0];
  assert.equal(canonical(before.html), canonical(after.html));
  assert.deepEqual(await read('/workspace'), excludedBefore);
  assert.deepEqual(await read('/missing'), missingBefore);
  assert.equal(excludedBefore.status, 401);
  assert.equal(missingBefore.status, 404);
  assert.equal(excludedBefore.robots, 'noindex');
  assert.equal(missingBefore.robots, 'noindex');
  assert.deepEqual(await read('/apps/export', 'Googlebot'), after);
  assert.throws(() => inspect(after.html.replace('"price":"39.00"', '"price":oops')), SyntaxError);
  mode = 'before';
  assert.deepEqual(await read('/apps/export'), before);
  console.log(JSON.stringify({
    node: process.version,
    before: beforeResult, after: afterResult,
    visibleBodyUnchanged: true, canonicalUnchanged: true,
    malformedJsonRejected: true, unrelatedOrganizationPreserved: true,
    excludedStatus: excludedBefore.status, missingStatus: missingBefore.status,
    userAgentResponseEqual: true, localRollbackEqual: true,
  }, null, 2));
} finally {
  await new Promise(resolve => server.close(resolve));
}
