param(
  [string]$AccountId = ""
)

$ErrorActionPreference = "Stop"
$PkgDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$AccountsDir = Join-Path $env:USERPROFILE ".accio\accounts"
if (!(Test-Path $AccountsDir)) {
  throw "Accio Work account directory not found: $AccountsDir"
}

if ([string]::IsNullOrWhiteSpace($AccountId)) {
  $accounts = Get-ChildItem -Path $AccountsDir -Directory | Sort-Object Name
  if ($accounts.Count -eq 1) {
    $AccountId = $accounts[0].Name
  } else {
    Write-Host "Multiple Accio Work accounts found. Pass -AccountId <account_id>."
    $accounts | ForEach-Object { Write-Host $_.Name }
    exit 1
  }
}

$Target = Join-Path $AccountsDir $AccountId
$BackupRoot = Join-Path $env:USERPROFILE ".accio\aios-install-backups"
$Stamp = Get-Date -Format "yyyyMMdd-HHmmss"
$Backup = Join-Path $BackupRoot "$AccountId-before-aios-p0-$Stamp"
New-Item -ItemType Directory -Force -Path $BackupRoot | Out-Null
Copy-Item -Path $Target -Destination $Backup -Recurse -Force

function Invoke-Python {
  param([string[]]$Args)
  $python = Get-Command python -ErrorAction SilentlyContinue
  if ($python) {
    & python @Args
  } else {
    & py -3 @Args
  }
}

Invoke-Python @("$PkgDir\validate_install.py", "--package", "$PkgDir", "--mode", "local", "--report", "$PkgDir\reports\install-windows-local-$Stamp.json")

Invoke-Python @("$PkgDir\validate_install.py", "--package", "$PkgDir", "--mode", "apply", "--target", "$Target", "--report", "$PkgDir\reports\install-windows-apply-$Stamp.json")
Invoke-Python @("$PkgDir\validate_install.py", "--package", "$PkgDir", "--mode", "verify", "--target", "$Target", "--report", "$PkgDir\reports\install-windows-verify-$Stamp.json")

Write-Host "AIOS AW P0 installed."
Write-Host "Target: $Target"
Write-Host "Backup: $Backup"
