import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fail, pass, repositoryRoot } from './lib.mjs';

const failures = [];
const analytics = await readFile(path.join(repositoryRoot, 'src/lib/analytics/events.ts'), 'utf8');
const client = await readFile(path.join(repositoryRoot, 'src/lib/analytics/client.ts'), 'utf8');
const dialog = await readFile(
  path.join(repositoryRoot, 'src/components/integrations/DemoDialogHost.tsx'),
  'utf8',
);

for (const forbidden of ['email', 'company', 'message', 'phone', 'fieldvalue', 'serverresponse']) {
  if (!analytics.toLowerCase().includes(`'${forbidden}'`)) {
    failures.push(`Analytics forbidden-key control omits ${forbidden}.`);
  }
}
if (!client.includes("dataset.analyticsConsent === 'granted'")) {
  failures.push('Analytics test adapter is not consent-gated.');
}
if (!client.includes("analyticsMode() !== 'test'")) {
  failures.push('Analytics adapter lacks an explicit disabled-by-default mode.');
}
if (/localStorage|sessionStorage/.test(dialog)) {
  failures.push('Demo form persists lead data in browser storage.');
}
if (/URLSearchParams|searchParams\.set/.test(dialog)) {
  failures.push('Demo form can place form data in a URL.');
}

if (failures.length) fail(failures);
else
  pass(
    'Phase 14 privacy controls prevent browser persistence, URL leakage, and unconsented analytics.',
  );
