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

// Simple .env loader
const envPath = path.join(__dirname, '.env');
if (fs.existsSync(envPath)) {
  const envConfig = fs.readFileSync(envPath, 'utf8');
  envConfig.split(/\r?\n/).forEach(line => {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) return;
    const parts = trimmed.split('=');
    if (parts.length >= 2) {
      const key = parts[0].trim();
      const value = parts.slice(1).join('=').trim();
      process.env[key] = value;
    }
  });
}

const PORT = process.env.PORT || 3000;
const logStream = fs.createWriteStream(path.join(__dirname, 'backend-debug.log'), { flags: 'a' });

function log(msg) {
  logStream.write(`[${new Date().toISOString()}] ${msg}\n`);
}

log("BACKEND STANDALONE STARTING");

// Start Strapi
const strapi = spawn('node', [path.join(__dirname, 'node_modules/@strapi/strapi/bin/strapi.js'), 'start'], {
  stdio: 'pipe',
  shell: true,
  cwd: __dirname,
  env: { ...process.env, PORT: PORT, NODE_ENV: 'production' }
});

strapi.stdout.on('data', (data) => logStream.write(`[Strapi] ${data}`));
strapi.stderr.on('data', (data) => logStream.write(`[Strapi ERR] ${data}`));

log(`MASTER LISTENING ON ${PORT} (Strapi instance)`);
