import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { prepareGitStaging } from './prepare-git-staging.mjs';

const temp = mkdtempSync(join(tmpdir(), 'vendoo-git-staging-'));
const source = join(temp, 'source');
const destination = join(temp, 'repo');
const write = (rel, value = rel) => {
  const target = join(source, rel);
  mkdirSync(join(target, '..'), { recursive: true });
  writeFileSync(target, value, 'utf8');
};

try {
  mkdirSync(source, { recursive: true });
  mkdirSync(join(destination, '.git'), { recursive: true });
  writeFileSync(join(destination, '.git', 'marker'), 'keep', 'utf8');
  writeFileSync(join(destination, 'old-file.txt'), 'remove', 'utf8');

  write('package.json', '{"name":"vendoo"}');
  write('.env.example', 'OPENAI_API_KEY=');
  write('.env.docker.example', 'VENDOO_SETUP_TOKEN=');
  write('.env.local', 'OPENAI_API_KEY=local-secret-should-never-copy');
  write('operations/staging/job.json', '{}');
  write('updates/backups/slice22_1_20260707-194953/scripts/install-local-flux.ps1', 'Write-Host local-backup');
  write('updates/backups/slice22_1_20260707-194953/setup.bat', '@echo local-backup');
  write('updates/backups/slice22_1_20260707-194953/setup.ps1', 'Write-Host local-backup');
  write('Archiv/Vendoo_Alt/vendoo/server.mjs', "import { missing } from './app/modules/inventory/routes.mjs';");
  write('logs/server.log', 'secret');
  write('modules/vendoo.ext-demo/package.vmod', '{"secret":"runtime-package"}');
  write('uploads/image.jpg', 'binary');
  write('db/vendoo.db', 'database');
  write('local-ai/comfyui/models/model.safetensors', 'model');
  write('docs/readme.md', '# safe');
  write('app/modules/listings/routes.mjs', 'export function registerListingsRoutes() {}');
  write('app/modules/inventory/index.mjs', 'export function configureInventoryModule() {}');
  write('app/modules/inventory/repository.mjs', 'export const inventoryRepository = {}');
  write('app/modules/inventory/routes.mjs', 'export function registerInventoryRoutes() {}');
  write('app/modules/sessions/index.mjs', 'export function configureSessionsModule() {}');

  const result = prepareGitStaging(source, destination);
  const required = ['package.json', '.env.example', '.env.docker.example', 'docs/readme.md', 'app/modules/listings/routes.mjs', 'app/modules/inventory/index.mjs', 'app/modules/inventory/repository.mjs', 'app/modules/inventory/routes.mjs', 'app/modules/sessions/index.mjs', '.git/marker'];
  const forbidden = ['old-file.txt', '.env.local', 'operations/staging/job.json', 'updates/backups/slice22_1_20260707-194953/scripts/install-local-flux.ps1', 'updates/backups/slice22_1_20260707-194953/setup.bat', 'updates/backups/slice22_1_20260707-194953/setup.ps1', 'Archiv/Vendoo_Alt/vendoo/server.mjs', 'logs/server.log', 'modules/vendoo.ext-demo/package.vmod', 'uploads/image.jpg', 'db/vendoo.db', 'local-ai/comfyui/models/model.safetensors'];
  for (const rel of required) {
    if (!existsSync(join(destination, rel))) throw new Error(`Pflichtdatei fehlt im Staging: ${rel}`);
  }
  for (const rel of forbidden) {
    if (existsSync(join(destination, rel))) throw new Error(`Verbotene Datei wurde kopiert: ${rel}`);
  }
  if (readFileSync(join(destination, '.git', 'marker'), 'utf8') !== 'keep') throw new Error('.git wurde verändert.');
  if (result.copied < 4 || result.skipped < 7) throw new Error('Staging-Zähler sind unplausibel.');
  console.log(`Git-Staging-Regressionstest erfolgreich: ${result.copied} sichere Dateien kopiert, ${result.skipped} lokale Einträge ausgeschlossen.`);
} finally {
  rmSync(temp, { recursive: true, force: true });
}
