import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const failures = [];
const required = [
  'VERSION', 'package.json', 'README.md', 'RELEASE_NOTES-v1.1.0.md', 'VALIDATION_REPORT.md',
  'BASLAT-WINDOWS.bat', 'BASLAT-LINUX-MAC.sh', 'Dockerfile', 'docker-compose.yml',
  'server/src/main.js', 'server/src/server.js', 'server/src/installer.js', 'server/src/admin-auth.js',
  'server/src/migrations.js', 'server/src/presale.js', 'server/src/wallets.js', 'server/src/distribution.js',
  'apps/installer/index.html', 'apps/installer/app.js', 'apps/website/app.js', 'apps/game/app.js', 'apps/admin/admin.js',
  'docs/PRODUCTION_INSTALLER.md', 'docs/FINAL_DEPLOYMENT.md', 'docs/DATABASE_RECOVERY.md'
];
for (const rel of required) {
  if (!fs.existsSync(path.join(root, rel))) failures.push(`Eksik zorunlu dosya: ${rel}`);
}

const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const version = fs.readFileSync(path.join(root, 'VERSION'), 'utf8').trim();
if (pkg.version !== version) failures.push(`Sürüm uyuşmazlığı: package=${pkg.version}, VERSION=${version}`);
if (version !== '1.1.0') failures.push(`Beklenen final sürüm 1.1.0, bulunan: ${version}`);

const forbiddenPaths = [
  '.env', 'node_modules', '.runtime', 'screenshots-v100',
  'scripts/start-demo.js', 'scripts/seed-demo.js', 'scripts/reset-and-seed.js', 'scripts/reset-db.js',
  'SIFIRLA-WINDOWS.bat', 'RELEASE_NOTES-v1.0.0.md',
  'data/installed.json', 'data/install.token',
  'data/onlycoin.db', 'data/onlycoin.db-wal', 'data/onlycoin.db-shm',
  'data/onlycoin-test.db', 'data/onlycoin-test.db-wal', 'data/onlycoin-test.db-shm'
];
for (const rel of forbiddenPaths) {
  if (fs.existsSync(path.join(root, rel))) failures.push(`Release içinde bulunmamalı: ${rel}`);
}

const forbiddenUserFacing = [
  /\/api\/auth\/demo/i,
  /\/api\/auth\/oauth\/demo/i,
  /Demo Kullanıcı/i,
  /Demo admin/i,
  /OnlyCoin-Admin-2026!/i,
  /temiz demo veritaban/i,
  /demo verileri/i
];
const userFacingRoots = [
  'apps/installer', 'apps/website', 'apps/game', 'apps/admin',
  'README.md', 'RELEASE_NOTES-v1.1.0.md', 'VALIDATION_REPORT.md',
  'KURULUM-WINDOWS.txt', 'ONCE-BUNU-OKUYUN.txt', 'docs'
];

function walk(entryPath, callback) {
  if (!fs.existsSync(entryPath)) return;
  const stat = fs.statSync(entryPath);
  if (stat.isFile()) return callback(entryPath);
  for (const entry of fs.readdirSync(entryPath, { withFileTypes: true })) {
    if (entry.name === '.git' || entry.name === 'recovery' || entry.name === 'backups') continue;
    walk(path.join(entryPath, entry.name), callback);
  }
}

for (const rel of userFacingRoots) {
  walk(path.join(root, rel), (file) => {
    if (!/\.(js|html|css|json|txt|md|bat|sh)$/i.test(file)) return;
    const value = fs.readFileSync(file, 'utf8');
    for (const pattern of forbiddenUserFacing) {
      if (pattern.test(value)) failures.push(`Canlı sürümde yasak ifade (${pattern}): ${path.relative(root, file)}`);
    }
  });
}

walk(root, (file) => {
  const stat = fs.statSync(file);
  if (stat.size >= 2_000_000 || !/\.(js|json|txt|md|env|example|yml|yaml|bat|cmd|ps1|sh)$/i.test(file)) return;
  const value = fs.readFileSync(file, 'utf8');
  if (/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(value)) failures.push(`Private key benzeri içerik: ${path.relative(root, file)}`);
  if (/\b(?:seed phrase|mnemonic)\s*[:=]\s*["'][a-z]+(?:\s+[a-z]+){11,23}["']/i.test(value)) failures.push(`Seed phrase benzeri içerik: ${path.relative(root, file)}`);
});

if (failures.length) {
  console.error('OnlyCoin release audit başarısız:');
  failures.forEach((item) => console.error(`- ${item}`));
  process.exit(1);
}
console.log(`OnlyCoin v${version} production installer release audit: PASS`);
