param(
  [string]$EnvPath = "",
  [switch]$Release,
  [switch]$Clean
)

$RepoRoot = $PSScriptRoot
$AppPath = Join-Path $RepoRoot "sojorn_app"
if ([string]::IsNullOrWhiteSpace($EnvPath)) {
  $EnvPath = Join-Path $RepoRoot ".env"
}
if (-not (Test-Path $AppPath)) {
  Write-Error "sojorn_app not found at ${AppPath}"
  exit 1
}
$flutterCmd = Get-Command flutter -ErrorAction SilentlyContinue
if ($flutterCmd) {
  $FlutterExe = $flutterCmd.Source
} else {
  $fallbackFlutter = "C:\Users\Patrick\develop\flutter\flutter\bin\flutter.bat"
  if (Test-Path $fallbackFlutter) {
    $FlutterExe = $fallbackFlutter
  } else {
    Write-Error "flutter command not found in PATH and fallback not found at $fallbackFlutter"
    exit 1
  }
}

function Get-EnvValues($path) {
  $vals = @{}
  if (-not (Test-Path $path)) {
    Write-Host "No .env file found at ${path}. Using defaults." -ForegroundColor Yellow
    # Set default API_BASE_URL since no .env exists
    $vals['API_BASE_URL'] = 'https://api.sojorn.net/api/v1'
    return $vals
  }
  Get-Content $path | ForEach-Object {
    $line = $_.Trim()
    if ($line.Length -eq 0 -or $line.StartsWith('#')) { return }
    $parts = $line -split '=', 2
    if ($parts.Count -lt 2) { return }
    $key = $parts[0].Trim()
    $value = $parts[1].Trim()
    if ($value.StartsWith('"') -and $value.EndsWith('"')) {
      $value = $value.Substring(1, $value.Length - 2)
    }
    $vals[$key] = $value
  }
  return $vals
}

$values = Get-EnvValues $EnvPath

# Collect dart-defines we actually use on Windows.
$defineArgs = @()
$keysOfInterest = @('API_BASE_URL', 'FIREBASE_WEB_VAPID_KEY', 'TURNSTILE_SITE_KEY')
foreach ($k in $keysOfInterest) {
  if ($values.ContainsKey($k) -and -not [string]::IsNullOrWhiteSpace($values[$k])) {
    $defineArgs += "--dart-define=$k=$($values[$k])"
  }
}

# Ensure API_BASE_URL is set
if (-not $values.ContainsKey('API_BASE_URL') -or [string]::IsNullOrWhiteSpace($values['API_BASE_URL'])) {
  $currentApi = 'https://api.sojorn.net/api/v1'
  $defineArgs += "--dart-define=API_BASE_URL=$currentApi"
}
else {
  $currentApi = $values['API_BASE_URL']
  if ($currentApi.StartsWith('http://localhost:')) {
    # For local development, keep localhost but warn
    Write-Host "Using local API: $currentApi" -ForegroundColor Yellow
  }
}

Write-Host "Building Sojorn for Windows..." -ForegroundColor Cyan
Write-Host "API: $currentApi"
Write-Host "Mode: $(if ($Release) { 'Release' } else { 'Debug' })"

Push-Location $AppPath
try {
  # Clean build if requested
  if ($Clean) {
    Write-Host "Cleaning build cache..." -ForegroundColor Yellow
    & $FlutterExe clean
    & $FlutterExe pub get
  }

  # Build for Windows
  $cmdArgs = @(
    'build',
    'windows'
  )
  
  if ($Release) {
    $cmdArgs += '--release'
  }
  else {
    $cmdArgs += '--debug'
  }
  
  $cmdArgs += $defineArgs

  Write-Host "Running: flutter $($cmdArgs -join ' ')" -ForegroundColor DarkGray
  & $FlutterExe $cmdArgs
  
  if ($LASTEXITCODE -eq 0) {
    $buildPath = Join-Path (Get-Location) "build\windows\x64\runner\Release"
    if (-not $Release) {
      $buildPath = Join-Path (Get-Location) "build\windows\x64\runner\Debug"
    }
    
    $exePath = Join-Path $buildPath "sojorn_app.exe"
    
    if (Test-Path $exePath) {
      Write-Host "Build successful!" -ForegroundColor Green
      Write-Host "Executable: $exePath" -ForegroundColor Cyan
      Write-Host "Build folder: $buildPath" -ForegroundColor Cyan
      
      # Ask if user wants to run the app
      $response = Read-Host "Do you want to run the app now? (y/n)"
      if ($response -eq 'y' -or $response -eq 'Y') {
        Write-Host "Starting Sojorn Windows app..." -ForegroundColor Yellow
        Start-Process -FilePath $exePath
      }
    }
    else {
      Write-Host "Build completed but executable not found at: $exePath" -ForegroundColor Red
    }
  }
  else {
    Write-Host "Build failed!" -ForegroundColor Red
  }
}
finally {
  Pop-Location
}
