#!/usr/bin/env node
/**
 * CI gate — shippable source must not contain hardcoded pilot hostnames.
 */
'use strict';

const fs = require('fs');
const path = require('path');

const root = path.resolve(__dirname, '..');
const forbidden = [Buffer.from('SkJHV0FMTFk=', 'base64').toString('utf8')];
const scanRoots = ['scripts', 'src', 'canvases', 'Discover-Sql.ps1', 'Discover-Deep.ps1', 'Discover-DBAOpsSovereign.ps1', 'Assess-ShipmentReadiness.ps1'];
const skipDirs = new Set(['node_modules', '__tests__', 'build', '_readiness', '_discovery', '_ship_readiness', 'pilot-before-website', 'dist', 'coverage']);
const skipFiles = new Set(['verify-portability.js']);
const hits = [];

function scanFile(file) {
  const rel = path.relative(root, file).replace(/\\/g, '/');
  if (skipFiles.has(path.basename(file))) return;
  if (skipDirs.has(path.basename(file))) return;
  const text = fs.readFileSync(file, 'utf8');
  for (const word of forbidden) {
    if (text.includes(word)) hits.push({ file: rel, word });
  }
}

function walk(dir) {
  if (!fs.existsSync(dir)) return;
  const stat = fs.statSync(dir);
  if (stat.isFile()) {
    if (/\.(ps1|js|jsx|ts|tsx|sql|json|md)$/i.test(dir)) scanFile(dir);
    return;
  }
  for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
    if (skipDirs.has(ent.name)) continue;
    walk(path.join(dir, ent.name));
  }
}

for (const r of scanRoots) walk(path.join(root, r));

if (hits.length) {
  console.error('[verify:portability] FAIL — hardcoded environment references:');
  hits.forEach((h) => console.error(`  ${h.word} in ${h.file}`));
  process.exit(1);
}
console.log('[verify:portability] OK — no hardcoded pilot hostnames in shippable source');
