#!/usr/bin/env node
/**
 * DBAOps Sovereign™ — friendly first-time setup (Windows, macOS, Linux)
 * Run from repo root:  node scripts/setup.js   or   npm run setup
 */

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const root = path.join(__dirname, '..');

function main() {
  const major = parseInt(process.version.slice(1).split('.')[0], 10);
  if (major < 18) {
    console.error('DBAOps Sovereign™ requires Node.js 18 or newer. Current:', process.version);
    process.exit(1);
  }

  const envExample = path.join(root, '.env.example');
  const envPath = path.join(root, '.env');
  if (!fs.existsSync(envPath) && fs.existsSync(envExample)) {
    fs.copyFileSync(envExample, envPath);
    console.log('Created .env from .env.example — edit SOVEREIGN_DB_CONNECTION when using SQL Server.');
  }

  const webEnvEx = path.join(root, 'src', 'web', '.env.example');
  const webEnv = path.join(root, 'src', 'web', '.env');
  if (!fs.existsSync(webEnv) && fs.existsSync(webEnvEx)) {
    fs.copyFileSync(webEnvEx, webEnv);
    console.log('Created src/web/.env — leave REACT_APP_API_URL empty for local dev (proxy).');
  }

  console.log('\nInstalling npm dependencies (root, API, web)…\n');
  execSync('npm install', { cwd: root, stdio: 'inherit' });

  const isWin = process.platform === 'win32';
  console.log('\n── DBAOps Sovereign™ is ready — RHOYLLE INNOVATION EMPIRE LLC ──\n');
  console.log('  Choose how to run:\n');
  console.log('  • Development (API + dashboard hot reload):');
  console.log('      npm start\n');
  console.log('  • All-in-one Docker (works the same on Windows, macOS, Linux):');
  console.log('      npm run docker:up\n');
  console.log('      Then open http://localhost:3000  ·  API http://localhost:3041\n');
  console.log('  • Shell helpers (macOS / Linux):');
  console.log('      chmod +x scripts/*.sh && ./scripts/run.sh\n');
  if (isWin) {
    console.log('  • Windows PowerShell:');
    console.log('      .\\scripts\\run.ps1\n');
  }
  console.log('  • Production build:  npm run build');
  console.log('  • Database migrate (when SQL is configured):  npm run migrate\n');
  console.log('Full guide: docs/INSTALL-CROSS-PLATFORM.md\n');
}

main();
