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

const rootDir = __dirname;
const backendDir = path.join(rootDir, 'pp_test_backend');
const frontDevDir = path.join(backendDir, 'frontDev');
const backendEnvExample = path.join(backendDir, '.env.example');
const backendEnvFile = path.join(backendDir, '.env');
const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm';

const args = new Set(process.argv.slice(2));
const buildFrontend = args.has('--build-frontend');
const syncDb = args.has('--sync-db');
const skipFrontend = args.has('--skip-frontend');
const skipBackend = args.has('--skip-backend');

function run(command, cwd) {
  execSync(command, {
    cwd,
    stdio: 'inherit',
    shell: true
  });
}

function ensureEnvFile() {
  if (fs.existsSync(backendEnvFile)) {
    return;
  }

  if (fs.existsSync(backendEnvExample)) {
    fs.copyFileSync(backendEnvExample, backendEnvFile);
    console.log('Created pp_test_backend/.env from .env.example');
  }
}

function checkNodeVersion() {
  const major = Number(process.versions.node.split('.')[0]);
  if (major < 18) {
    throw new Error(`Node.js 18 or newer is required. Current version: ${process.versions.node}`);
  }
}

function main() {
  checkNodeVersion();
  ensureEnvFile();

  if (!skipBackend) {
    console.log('Installing backend dependencies...');
    run(`${npmCommand} install`, backendDir);
  }

  if (!skipFrontend) {
    console.log('Installing frontend dependencies...');
    run(`${npmCommand} install`, frontDevDir);

    if (buildFrontend) {
      console.log('Building frontend...');
      run(`${npmCommand} run build`, frontDevDir);
    }
  }

  if (syncDb) {
    console.log('Syncing database schema...');
    run('node alter.js', backendDir);
  }

  console.log('Setup complete. Next steps:');
  console.log('1. Update pp_test_backend/.env with your database and session settings if needed.');
  console.log('2. Run node alter.js from pp_test_backend to sync the schema, or use --sync-db.');
  console.log('3. Run node main.js from pp_test_backend to start the backend.');
}

try {
  main();
} catch (error) {
  console.error(error.message || error);
  process.exit(1);
}
