param(
  [switch]$FrontendOnly,
  [switch]$BackendOnly,
  [switch]$AdminOnly,
  [switch]$McpOnly,
  [switch]$WithMcp,
  [string]$DatabaseUrl = "postgres://postgres:postgres%402025%21@10.0.0.2:5432/termi-api_development",
  [string]$McpApiKey = "termi-mcp-local-dev-key",
  [string]$BackendApiBase = "http://127.0.0.1:5150/api",
  [int]$McpPort = 5151
)

$ErrorActionPreference = "Stop"

$repoRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$stopScript = Join-Path $repoRoot "stop-services.ps1"
$devScript = Join-Path $repoRoot "dev.ps1"

if (@($FrontendOnly, $BackendOnly, $AdminOnly, $McpOnly).Where({ $_ }).Count -gt 1) {
  throw "Use only one of -FrontendOnly, -BackendOnly, -AdminOnly, or -McpOnly."
}

Write-Host "[restart] Stopping target services first..." -ForegroundColor Cyan

if ($FrontendOnly) {
  & $stopScript -FrontendOnly
}
elseif ($BackendOnly) {
  & $stopScript -BackendOnly
}
elseif ($AdminOnly) {
  & $stopScript -AdminOnly
}
elseif ($McpOnly) {
  & $stopScript -McpOnly
}
else {
  & $stopScript -WithMcp:$WithMcp
}

Start-Sleep -Seconds 1

if ($FrontendOnly) {
  & $devScript -Only frontend -Spawn
  Write-Host "[restart] Frontend tab restarted." -ForegroundColor Green
  exit 0
}

if ($BackendOnly) {
  & $devScript -Only backend -Spawn -DatabaseUrl $DatabaseUrl
  Write-Host "[restart] Backend tab restarted." -ForegroundColor Green
  exit 0
}

if ($AdminOnly) {
  & $devScript -Only admin -Spawn
  Write-Host "[restart] Admin tab restarted." -ForegroundColor Green
  exit 0
}

if ($McpOnly) {
  & $devScript -Only mcp -Spawn -McpApiKey $McpApiKey -McpBackendApiBase $BackendApiBase -McpPort $McpPort
  Write-Host "[restart] MCP tab restarted." -ForegroundColor Green
  exit 0
}

& $devScript -DatabaseUrl $DatabaseUrl -WithMcp:$WithMcp
