$Root = Split-Path $PSScriptRoot -Parent
Set-Location $Root

. "$PSScriptRoot\db-local.ps1"

Write-Host '================================'
Write-Host ' EENE Dashboard - Start'
Write-Host ' Data: data/postgres, uploads/'
Write-Host '================================'
Write-Host ''

foreach ($dir in @('data', 'data\postgres', 'data\seed', 'uploads\team')) {
  $p = Join-Path $Root $dir
  if (-not (Test-Path $p)) { New-Item -ItemType Directory -Force -Path $p | Out-Null }
}

$envPath = Join-Path $Root 'backend\.env'
$envExample = Join-Path $Root 'backend\.env.example'
if (-not (Test-Path $envPath)) {
  Write-Host '[Setup] Creating backend\.env ...'
  Copy-Item $envExample $envPath
  Write-Host '        Done.'
  Write-Host ''
}

Ensure-BackendEnv -Root $Root

Write-Host '[1/4] Stopping existing API/WEB ...'
& "$PSScriptRoot\kill-ports.ps1" | Out-Null
Start-Sleep -Seconds 1
Write-Host '        Done.'
Write-Host ''

Write-Host '[2/4] Starting database (data\postgres) ...'
$dbMode = 'unknown'

if (Test-DockerReady) {
  if (Test-Path (Join-Path $Root 'docker-compose.yml')) {
    docker compose up -d 2>$null
    if ($LASTEXITCODE -eq 0) { $dbMode = 'docker' }
  }
}

if ($dbMode -eq 'unknown') {
  $dbRc = & "$PSScriptRoot\start-local-db.ps1"
  if ($dbRc -eq 0) { $dbMode = 'local' }
}

if ($dbMode -eq 'unknown') {
  Write-Host ''
  Write-Host ' [ERROR] Cannot start database.'
  Write-Host ' - Install PostgreSQL 16 (initdb/pg_ctl in PATH), or'
  Write-Host ' - Install Docker Desktop and retry'
  Write-Host ''
  exit 1
}

Write-Host "        DB: $dbMode (port 54320, data\postgres)"

if ($dbMode -eq 'docker') {
  $waitRc = & "$PSScriptRoot\wait-db.ps1" -Port 54320
  if ($waitRc -ne 0) { exit 1 }
}
Write-Host ''

Write-Host '[3/4] DB schema + seed if empty ...'
Set-Location (Join-Path $Root 'backend')
if (-not (Test-Path 'node_modules')) {
  Write-Host '        npm install (backend) ...'
  cmd /c 'npm install'
  if ($LASTEXITCODE -ne 0) { exit 1 }
}
cmd /c 'npm run db:sync'
if ($LASTEXITCODE -ne 0) {
  Write-Host '[ERROR] npm run db:sync failed'
  exit 1
}
cmd /c 'npm run db:seed-if-empty'
if ($LASTEXITCODE -ne 0) {
  Write-Host '[ERROR] npm run db:seed-if-empty failed'
  exit 1
}
cmd /c 'npm run db:seed-team-if-empty'
if ($LASTEXITCODE -ne 0) {
  Write-Host '[ERROR] npm run db:seed-team-if-empty failed'
  exit 1
}
cmd /c 'npx prisma generate'
if ($LASTEXITCODE -ne 0) {
  Write-Host '[ERROR] prisma generate failed (stop other servers and retry)'
  exit 1
}
Set-Location $Root
Write-Host '        Done.'
Write-Host ''

Write-Host '[4/4] Starting API + WEB ...'
if (-not (Test-Path (Join-Path $Root 'frontend\node_modules'))) {
  Write-Host '        npm install (frontend) ...'
  Set-Location (Join-Path $Root 'frontend')
  cmd /c 'npm install'
  if ($LASTEXITCODE -ne 0) { exit 1 }
  Set-Location $Root
}

$lanIp = $null
try {
  $ip = & "$PSScriptRoot\get-lan-ip.ps1" 2>$null
  if ($ip) { $lanIp = $ip.Trim() }
} catch { }

if (-not $lanIp) {
  Write-Host ' [WARN] LAN IP not detected — HTTPS for team may not start.'
  Write-Host '        Set EENE_LAN_IP=172.16.8.248 if needed.'
}

$backend = Join-Path $Root 'backend'
$frontend = Join-Path $Root 'frontend'
if ($lanIp) {
  Set-Content -Path (Join-Path $frontend '.lan-ip') -Value $lanIp -NoNewline -Encoding ascii
} elseif (Test-Path (Join-Path $frontend '.lan-ip')) {
  Remove-Item (Join-Path $frontend '.lan-ip') -Force
}

Write-Host ''
Write-Host ' Local     : http://localhost:3000  (듀얼 모니터, 인증서 없음)'
Write-Host ' Admin     : http://localhost:3000/admin'
if ($lanIp) {
  Write-Host " LAN       : https://${lanIp}:3000  (인증서 경고 → 고급 → 계속 → 허용)"
} else {
  Write-Host ' LAN       : (IP 미감지 — EENE_LAN_IP 환경변수 설정 후 재시작)'
}
Write-Host ' Stop      : 서버종료.bat'
Write-Host '================================'
Write-Host ''

$webCmds = @(
  "cd /d `"$backend`" && npm run dev:serve",
  "cd /d `"$frontend`" && npx --yes wait-on -t 90000 http://127.0.0.1:4000/health && npx vite --mode http-local --host localhost"
)
if ($lanIp) {
  $webCmds += "cd /d `"$frontend`" && npx --yes wait-on -t 90000 http://127.0.0.1:4000/health && npx vite --mode https-lan --host $lanIp"
}
$names = if ($lanIp) { 'API,WEB-HTTP,WEB-HTTPS' } else { 'API,WEB-HTTP' }
$colors = if ($lanIp) { 'cyan,green,yellow' } else { 'cyan,green' }
npx --yes concurrently -k -n $names -c $colors $webCmds

Write-Host ''
Write-Host ' Server stopped.'
