$PSScriptRoot = Get-Location

# --- CONFIGURATION ---
$REDIS_CMD = "redis-server"
$BACKEND_DIR = Join-Path $PSScriptRoot "backend"
$ML_DIR = Join-Path $PSScriptRoot "ml_service"
$FRONTEND_DIR = Join-Path $PSScriptRoot "frontend\syncfrontend"

Write-Host "Starting SYNC Project..." -ForegroundColor Cyan

# 1. Start Redis
Write-Host "Starting Redis..." -ForegroundColor Yellow
# Using 127.0.0.1 explicitly for Redis
Start-Process powershell -ArgumentList "-NoExit", "-Command", "Write-Host 'REDIS SERVER'; $REDIS_CMD --bind 127.0.0.1"

# 2. Start ML Service
Write-Host "Starting ML Service..." -ForegroundColor Yellow
$ML_VENV_PYTHON = Join-Path $ML_DIR ".venv\Scripts\python.exe"
$ML_CMD = "cd '$ML_DIR'; Write-Host 'ML SERVICE'; & '$ML_VENV_PYTHON' run.py"
Start-Process powershell -ArgumentList "-NoExit", "-Command", "$ML_CMD"

# 3. Start Backend Django
Write-Host "Starting Backend Django..." -ForegroundColor Yellow
$BACKEND_VENV_PYTHON = Join-Path $BACKEND_DIR ".venv\Scripts\python.exe"
$DJANGO_CMD = "cd '$BACKEND_DIR'; Write-Host 'DJANGO BACKEND'; & '$BACKEND_VENV_PYTHON' manage.py runserver"
Start-Process powershell -ArgumentList "-NoExit", "-Command", "$DJANGO_CMD"

# 4. Start Backend Celery
Write-Host "Starting Backend Celery..." -ForegroundColor Yellow
$CELERY_CMD = "cd '$BACKEND_DIR'; Write-Host 'CELERY WORKER'; & '$BACKEND_VENV_PYTHON' -m celery -A sync_backend worker -l info --pool=solo"
Start-Process powershell -ArgumentList "-NoExit", "-Command", "$CELERY_CMD"

# 5. Start Frontend
Write-Host "Starting Frontend..." -ForegroundColor Yellow
$FRONTEND_CMD = "cd '$FRONTEND_DIR'; Write-Host 'FRONTEND VITE'; npm run dev"
Start-Process powershell -ArgumentList "-NoExit", "-Command", "$FRONTEND_CMD"

Write-Host "All services initiated in separate windows." -ForegroundColor Green
Write-Host "Note: If Celery has trouble connecting to Redis, ensure .env uses 127.0.0.1 instead of localhost."
Write-Host "Press Enter to exit this starter script..."
Read-Host
