const path = require('path')
const fs = require('fs')

const root = path.resolve(__dirname, '../..')
const envPath = path.join(root, '.env')

function loadEnv() {
  const env = { NODE_ENV: 'production' }
  if (!fs.existsSync(envPath)) return env
  for (const line of fs.readFileSync(envPath, 'utf8').split('\n')) {
    const trimmed = line.trim()
    if (!trimmed || trimmed.startsWith('#')) continue
    const idx = trimmed.indexOf('=')
    if (idx === -1) continue
    const key = trimmed.slice(0, idx).trim()
    let value = trimmed.slice(idx + 1).trim()
    if (
      (value.startsWith('"') && value.endsWith('"')) ||
      (value.startsWith("'") && value.endsWith("'"))
    ) {
      value = value.slice(1, -1)
    }
    env[key] = value
  }
  return env
}

const env = loadEnv()
const webPort = env.WEB_PORT || '23566'
const apiPort = env.API_PORT || '23568'
const venvPython = path.join(root, 'backend', 'venv', 'bin', 'python')

module.exports = {
  apps: [
    {
      name: 'grade-api',
      cwd: path.join(root, 'backend'),
      script: venvPython,
      args: `-m uvicorn app.main:app --host 127.0.0.1 --port ${apiPort}`,
      interpreter: 'none',
      env: {
        ...env,
        UPLOAD_DIR: env.UPLOAD_DIR || path.join(root, 'uploads'),
      },
      max_restarts: 10,
      restart_delay: 5000,
    },
    {
      name: 'grade-web',
      cwd: path.join(root, 'deploy', 'pm2'),
      script: 'server.js',
      env: {
        ...env,
        WEB_PORT: webPort,
        API_TARGET: env.API_TARGET || `http://127.0.0.1:${apiPort}`,
      },
      max_restarts: 10,
      restart_delay: 3000,
    },
  ],
}
