import { spawn } from 'child_process'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const dropsDir = path.join(__dirname, '../drops')

// Get drop name from command line args
const dropName = process.argv[2]

if (!dropName) {
    console.error('❌ Error: Please specify a drop name')
    console.log('Usage: npm run dev <drop-name>')
    console.log('\nAvailable drops:')
    const drops = fs
        .readdirSync(dropsDir, { withFileTypes: true })
        .filter((dirent) => dirent.isDirectory())
        .map((dirent) => dirent.name)
    drops.forEach((drop) => console.log(`  - ${drop}`))
    process.exit(1)
}

const dropPath = path.join(dropsDir, dropName)

if (!fs.existsSync(dropPath)) {
    console.error(`❌ Error: Drop "${dropName}" does not exist`)
    process.exit(1)
}

console.log(`\n🚀 Starting dev environment for: ${dropName}\n`)
console.log(`📦 Drop dev server: http://localhost:3000`)
console.log(`📝 CMS: http://localhost:8787\n`)

// Start drop dev server
const dropProcess = spawn('npm', ['run', 'dev'], {
    cwd: dropPath,
    stdio: 'inherit',
    shell: true,
})

// Start CMS with DROP_NAME environment variable
const cmsProcess = spawn('npm', ['run', 'dev', '-w', 'cms'], {
    cwd: path.join(__dirname, '..'),
    stdio: 'inherit',
    shell: true,
    env: {
        ...process.env,
        DROP_NAME: dropName,
    },
})

// Handle process cleanup
const cleanup = () => {
    console.log('\n\n🛑 Shutting down dev servers...')
    dropProcess.kill()
    cmsProcess.kill()
    process.exit(0)
}

process.on('SIGINT', cleanup)
process.on('SIGTERM', cleanup)

dropProcess.on('error', (err) => {
    console.error('❌ Drop server error:', err)
    cleanup()
})

cmsProcess.on('error', (err) => {
    console.error('❌ CMS server error:', err)
    cleanup()
})
