Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$backendDir = Split-Path -Parent $scriptDir

Set-Location $backendDir

$env:APP_ENV = if ($env:APP_ENV) { $env:APP_ENV } else { "development" }
$env:HTTP_ADDR = if ($env:HTTP_ADDR) { $env:HTTP_ADDR } else { ":18090" }
$env:DATABASE_URL = if ($env:DATABASE_URL) { $env:DATABASE_URL } else { "postgres://postgres:asdf*123@192.168.100.77:5432/cmr20260401?sslmode=disable" }
$env:JWT_ACCESS_SECRET = if ($env:JWT_ACCESS_SECRET) { $env:JWT_ACCESS_SECRET } else { "change-me-in-production" }
$env:AUTH_SMS_PROVIDER = if ($env:AUTH_SMS_PROVIDER) { $env:AUTH_SMS_PROVIDER } else { "console" }
$env:WECHAT_MINI_DEV_PREFIX = if ($env:WECHAT_MINI_DEV_PREFIX) { $env:WECHAT_MINI_DEV_PREFIX } else { "dev-" }
$env:LOCAL_EVENT_DIR = if ($env:LOCAL_EVENT_DIR) { $env:LOCAL_EVENT_DIR } else { "D:\dev\cmr-mini\event" }
$env:ASSET_BASE_URL = if ($env:ASSET_BASE_URL) { $env:ASSET_BASE_URL } else { "https://oss-mbh5.colormaprun.com/gotomars" }
$env:ASSET_PUBLIC_BASE_URL = if ($env:ASSET_PUBLIC_BASE_URL) { $env:ASSET_PUBLIC_BASE_URL } else { "https://oss-mbh5.colormaprun.com" }
$env:ASSET_BUCKET_ROOT = if ($env:ASSET_BUCKET_ROOT) { $env:ASSET_BUCKET_ROOT } else { "oss://color-map-html" }
$env:OSSUTIL_PATH = if ($env:OSSUTIL_PATH) { $env:OSSUTIL_PATH } else { "D:\dev\cmr-mini\tools\ossutil.exe" }
$env:OSSUTIL_CONFIG_FILE = if ($env:OSSUTIL_CONFIG_FILE) { $env:OSSUTIL_CONFIG_FILE } else { (Join-Path $HOME ".ossutilconfig") }

if (-not (Test-Path $env:LOCAL_EVENT_DIR)) {
  throw ("LOCAL_EVENT_DIR not found: " + $env:LOCAL_EVENT_DIR)
}

if (-not (Test-Path $env:OSSUTIL_PATH)) {
  Write-Warning ("OSSUTIL_PATH not found: " + $env:OSSUTIL_PATH)
}

if (-not (Test-Path $env:OSSUTIL_CONFIG_FILE)) {
  Write-Warning ("OSSUTIL_CONFIG_FILE not found: " + $env:OSSUTIL_CONFIG_FILE)
}

Write-Host "CMR backend dev server" -ForegroundColor Cyan
Write-Host ("APP_ENV=" + $env:APP_ENV)
Write-Host ("HTTP_ADDR=" + $env:HTTP_ADDR)
Write-Host ("DATABASE_URL=" + $env:DATABASE_URL)
Write-Host ("LOCAL_EVENT_DIR=" + $env:LOCAL_EVENT_DIR)
Write-Host ("ASSET_BASE_URL=" + $env:ASSET_BASE_URL)
Write-Host ""
Write-Host "Workbench:" -ForegroundColor Yellow
$workbenchAddr = $env:HTTP_ADDR
if ($workbenchAddr.StartsWith(":")) {
  $workbenchAddr = "127.0.0.1" + $workbenchAddr
}
Write-Host ("http://" + $workbenchAddr + "/dev/workbench")
Write-Host ""

$exePath = Join-Path $backendDir "cmr-backend.exe"

Write-Host "Build:" -ForegroundColor Yellow
Write-Host $exePath
Write-Host ""

go build -o $exePath .\cmd\api
if ($LASTEXITCODE -ne 0) {
  throw "go build failed"
}

& $exePath
