import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';

console.log('=============================================');
console.log('  TOPBD Production Build Engine starting...  ');
console.log('=============================================');

try {
  // 1. Vite build (frontend)
  console.log('[1/4] Building frontend with Vite...');
  execSync('npx vite build', { stdio: 'inherit' });

  // 2. esbuild (backend server.ts)
  console.log('[2/4] Bundling server.ts with esbuild...');
  execSync('npx esbuild server.ts --bundle --platform=node --format=cjs --packages=external --sourcemap --outfile=dist/server.cjs', { stdio: 'inherit' });

  // 3. Verification
  const distIndex = path.join(process.cwd(), 'dist', 'index.html');
  const distServer = path.join(process.cwd(), 'dist', 'server.cjs');

  if (!fs.existsSync(distIndex) || !fs.existsSync(distServer)) {
    throw new Error('Build output missing dist/index.html or dist/server.cjs');
  }

  const htmlContent = fs.readFileSync(distIndex, 'utf-8');
  if (htmlContent.includes('/src/main.tsx')) {
    throw new Error('Build failed: dist/index.html references uncompiled /src/main.tsx!');
  }
  console.log('[3/4] Verified compiled frontend index.html assets reference /assets/*.js!');

  // 4. Sync dist to production_dist, dist_cpanel, cpanel_dist, and root server.cjs
  const targets = ['production_dist', 'dist_cpanel', 'cpanel_dist'];
  for (const target of targets) {
    const targetPath = path.join(process.cwd(), target);
    if (fs.existsSync(targetPath)) {
      fs.rmSync(targetPath, { recursive: true, force: true });
    }
    fs.cpSync(path.join(process.cwd(), 'dist'), targetPath, { recursive: true });
    console.log(` -> Synced to ${target}/`);
  }

  // Sync compiled assets/ to dist targets
  const rootAssets = path.join(process.cwd(), 'assets');
  if (fs.existsSync(rootAssets)) {
    fs.rmSync(rootAssets, { recursive: true, force: true });
  }
  fs.cpSync(path.join(process.cwd(), 'dist', 'assets'), rootAssets, { recursive: true });
  console.log(' -> Synced compiled assets/ to workspace root assets/');

  // Generate .htaccess for cPanel Apache / Passenger MIME & DirectoryIndex handling
  const htaccessContent = `# cPanel / Apache Phusion Passenger Configuration
DirectoryIndex disabled

<IfModule mod_mime.c>
  AddType application/javascript .js .mjs
  AddType text/css .css
  AddType image/svg+xml .svg
  AddType application/json .json
</IfModule>
`;
  fs.writeFileSync(path.join(process.cwd(), '.htaccess'), htaccessContent);
  fs.writeFileSync(path.join(process.cwd(), 'production_dist', '.htaccess'), htaccessContent);
  console.log(' -> Created .htaccess in root and production_dist/');

  // Copy server.cjs to root for cPanel environments pointing to server.cjs in app root
  fs.copyFileSync(distServer, path.join(process.cwd(), 'server.cjs'));
  if (fs.existsSync(distServer + '.map')) {
    fs.copyFileSync(distServer + '.map', path.join(process.cwd(), 'server.cjs.map'));
  }
  console.log('[4/5] Copied server.cjs to workspace root for cPanel startup compatibility.');

  // 5. Create deployment ZIP containing production_dist, dist, server.cjs, etc.
  console.log('[5/5] Packaging topbd_cpanel_deploy.zip archive...');
  execSync(`python3 -c "import os, zipfile; z = zipfile.ZipFile('topbd_cpanel_deploy.zip', 'w', zipfile.ZIP_DEFLATED); [z.write(os.path.join(r, f), os.path.relpath(os.path.join(r, f), '.')) for r, d, files in os.walk('.') if not any(x in r for x in ['node_modules', '.git', 'topbd_cpanel_deploy.zip']) for f in files if f != 'topbd_cpanel_deploy.zip']; z.close()"` );
  
  if (fs.existsSync('public')) {
    fs.copyFileSync('topbd_cpanel_deploy.zip', 'public/topbd_cpanel_deploy.zip');
  }
  fs.copyFileSync('topbd_cpanel_deploy.zip', 'production_dist/topbd_cpanel_deploy.zip');
  console.log(' -> Created topbd_cpanel_deploy.zip in root, production_dist/, and public/');

  console.log('=============================================');
  console.log('  Build Completed Successfully!              ');
  console.log('=============================================');
} catch (err) {
  console.error('Build Error:', err);
  process.exit(1);
}
