$ErrorActionPreference = "Stop"

$installDir = $env:FASHION_AI_INSTALL_DIR
if (-not $installDir) {
  $installDir = Join-Path $env:ProgramFiles "FashionAIDesignStudio"
}
$dataRoot = Join-Path $env:ProgramData "FashionAIDesignStudio"
$dataDir = Join-Path $dataRoot "data"
$logDir = Join-Path $dataRoot "logs"
$serviceName = "FashionAIDesignStudio"

New-Item -ItemType Directory -Path $installDir -Force | Out-Null
New-Item -ItemType Directory -Path $dataDir -Force | Out-Null
New-Item -ItemType Directory -Path $logDir -Force | Out-Null

$nodeExe = Join-Path $installDir "node.exe"
if (!(Test-Path $nodeExe)) {
  $nodeExe = "node.exe"
}
$launcher = Join-Path $installDir "tools\exe\server-launcher.mjs"
if (!(Test-Path $launcher)) {
  throw "server-launcher.mjs not found: $launcher"
}

$envFile = Join-Path $installDir ".env"
$envExample = Join-Path $installDir ".env.example"
if (!(Test-Path $envFile) -and (Test-Path $envExample)) {
  Copy-Item -LiteralPath $envExample -Destination $envFile -Force
}

$binPath = "`"$nodeExe`" `"$launcher`""
$existing = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($existing) {
  Stop-Service -Name $serviceName -ErrorAction SilentlyContinue
  sc.exe delete $serviceName | Out-Null
}

New-Service -Name $serviceName -BinaryPathName $binPath -DisplayName "Fashion AI Design Studio" -StartupType Automatic | Out-Null
Start-Service -Name $serviceName
Write-Host "[Done] Windows service installed and started: $serviceName"
