param(
  [string]$BaseUrl = $env:SKILL_CLI_BASE_URL,
  [string]$Version = $env:SKILL_CLI_VERSION,
  [string]$InstallDir = $env:SKILL_CLI_INSTALL_DIR,
  [string]$ClaudeDir = $env:SKILL_CLI_CLAUDE_DIR,
  [ValidateSet("lite", "full", "none")]
  [string]$Doctor = $(if ($env:SKILL_CLI_DOCTOR) { $env:SKILL_CLI_DOCTOR } else { "lite" }),
  [switch]$NoInstall,
  [switch]$NoPathUpdate,
  [switch]$DryRun
)

$ErrorActionPreference = "Stop"

function Test-TruthyEnv {
  param([string]$Value)
  if (-not $Value) {
    return $false
  }
  return @("1", "true", "yes", "on") -contains $Value.ToLowerInvariant()
}

if (Test-TruthyEnv $env:SKILL_CLI_NO_INSTALL) {
  $NoInstall = $true
}

if (Test-TruthyEnv $env:SKILL_CLI_NO_PATH_UPDATE) {
  $NoPathUpdate = $true
}

if (Test-TruthyEnv $env:SKILL_CLI_DRY_RUN) {
  $DryRun = $true
}

$baseUrlWasProvided = [bool]$BaseUrl

if (-not $Version) {
  $Version = "v0.13.28"
}

if (-not $BaseUrl) {
  $BaseUrl = "https://gitee.com/marvin-dev/skill-cli-creator/raw/$Version/bin/targets"
}

if (-not $InstallDir) {
  $InstallDir = Join-Path $env:LOCALAPPDATA "Programs\skill-cli"
}

if (-not [Environment]::Is64BitOperatingSystem) {
  throw "skill-cli currently provides a Windows x64 binary only."
}

$asset = "skill-cli-win32-x64.exe"
$url = ($BaseUrl.TrimEnd("/")) + "/" + $asset
$target = Join-Path $InstallDir "skill-cli.exe"

Write-Host "skill-cli installer"
Write-Host "  asset:      $asset"
Write-Host "  source:     $url"
Write-Host "  target:     $target"
if (-not $baseUrlWasProvided) {
  Write-Host "  version:    $Version"
}
if ($ClaudeDir) {
  Write-Host "  claude dir: $ClaudeDir"
}

if ($DryRun) {
  Write-Host "dry run: no files written"
  return
}

$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("skill-cli-install-" + [Guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Path $tmp -Force | Out-Null

try {
  $downloaded = Join-Path $tmp $asset
  $downloadedOk = $false
  for ($attempt = 1; $attempt -le 3; $attempt++) {
    try {
      Invoke-WebRequest -Uri $url -OutFile $downloaded -UseBasicParsing
      $downloadedOk = $true
      break
    } catch {
      if ($attempt -eq 3) {
        throw
      }
      Start-Sleep -Seconds (2 * $attempt)
    }
  }
  if (-not $downloadedOk) {
    throw "download failed: $url"
  }
  New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
  Copy-Item -LiteralPath $downloaded -Destination $target -Force

  try {
    Unblock-File -LiteralPath $target
  } catch {
    # Unblock-File can fail on filesystems without Zone.Identifier streams.
  }

  if (-not $NoPathUpdate) {
    $userPath = [Environment]::GetEnvironmentVariable("Path", "User")
    $parts = @()
    if ($userPath) {
      $parts = $userPath -split ';' | Where-Object { $_ }
    }
    $alreadyInPath = $false
    foreach ($part in $parts) {
      if ([string]::Equals($part.TrimEnd('\'), $InstallDir.TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase)) {
        $alreadyInPath = $true
        break
      }
    }
    if (-not $alreadyInPath) {
      $newPath = if ($userPath) { "$userPath;$InstallDir" } else { $InstallDir }
      [Environment]::SetEnvironmentVariable("Path", $newPath, "User")
      $env:Path = "$env:Path;$InstallDir"
      Write-Host "  PATH:       added to current user PATH"
    }
  }

  Write-Host ""
  & $target version

  $claudeArgs = @()
  if ($ClaudeDir) {
    $claudeArgs += @("--claude-dir", $ClaudeDir)
  }

  if (-not $NoInstall) {
    Write-Host ""
    & $target install @claudeArgs
  }

  if ($Doctor -eq "lite") {
    Write-Host ""
    & $target doctor @claudeArgs --check-adversarial=false
  } elseif ($Doctor -eq "full") {
    Write-Host ""
    & $target doctor @claudeArgs
  }

  Write-Host ""
  Write-Host "skill-cli install complete."
  Write-Host "Open a new terminal and run: skill-cli doctor"
} finally {
  Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue
}
