#!/usr/bin/env node

import { spawn } from 'child_process'
import { existsSync } from 'fs'
import { dirname, resolve } from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const projectRoot = process.cwd()
const sdkRoot = resolve(__dirname, '..')

console.log('🚀 BMDL SDK Development Server')
console.log('═══════════════════════════════════════')
console.log(`📂 Project root: ${projectRoot}`)
console.log(`📦 SDK root: ${sdkRoot}`)
console.log('═══════════════════════════════════════')

// Проверяем наличие необходимых файлов в проекте
const requiredFiles = [
  'src/app/App.tsx',
  'src/config.ts',
  'src/dataOptions.ts',
  'src/viewOptions.ts',
]

let missingFiles = []
requiredFiles.forEach(file => {
  const fullPath = resolve(projectRoot, file)
  if (!existsSync(fullPath)) {
    missingFiles.push(file)
  }
})

if (missingFiles.length > 0) {
  console.log('⚠️  Missing required files in your project:')
  missingFiles.forEach(file => console.log(`   ❌ ${file}`))
  console.log('')
  console.log('💡 Run "npx bmdl-sdk init" to create the missing files')
  console.log('')
} else {
  console.log('✅ All required files found')
}

console.log('')
console.log('🔧 Starting Vite development server...')
console.log('🌐 http://localhost:3000')
console.log('')

const next = spawn(
  'npx',
  ['next', 'dev', '--port', '3000', '--experimental-app'],
  {
    stdio: 'inherit',
    shell: true,
    cwd: sdkRoot,
    env: {
      ...process.env,
      PROJECT_ROOT: projectRoot,
      NODE_ENV: 'development',
      NEXT_PUBLIC_PROJECT_ROOT: projectRoot,
    },
  }
);


next.on('close', code => {
  if (code !== 0) {
    console.log(`❌ Next.js process exited with code ${code}`)
  }
  process.exit(code)
})
