param(
  [string]$InstallRoot = "C:\Program Files\ProxyWarden\ControlApp",
  [string]$DataRoot = "C:\ProgramData\ProxyWarden",
  [switch]$PlanOnly,
  [switch]$Force
)

$ErrorActionPreference = "Stop"

function New-Result {
  param(
    [bool]$Success,
    [string]$Action,
    [bool]$Changed,
    [string]$Message,
    [hashtable]$Details = @{}
  )

  [ordered]@{
    success = $Success
    action = $Action
    changed = $Changed
    message = $Message
    details = $Details
  } | ConvertTo-Json -Depth 6
}

function Test-IsAdministrator {
  $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
  $principal = [Security.Principal.WindowsPrincipal]::new($identity)
  $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

function Ensure-Directory {
  param([string]$Path)
  if (-not (Test-Path -LiteralPath $Path)) {
    New-Item -ItemType Directory -Path $Path -Force | Out-Null
    return $true
  }
  return $false
}

try {
  $details = @{
    installRoot = $InstallRoot
    dataRoot = $DataRoot
    planOnly = [bool]$PlanOnly
  }

  if ($PlanOnly) {
    New-Result -Success $true -Action "install-control-app" -Changed $false -Message "Control App install plan is ready." -Details $details
    exit 0
  }

  if (-not (Test-IsAdministrator)) {
    New-Result -Success $false -Action "install-control-app" -Changed $false -Message "Administrator rights are required." -Details $details
    exit 1
  }

  $changed = $false
  $changed = (Ensure-Directory -Path $InstallRoot) -or $changed
  $changed = (Ensure-Directory -Path (Join-Path $DataRoot "config")) -or $changed
  $changed = (Ensure-Directory -Path (Join-Path $DataRoot "state")) -or $changed
  $changed = (Ensure-Directory -Path (Join-Path $DataRoot "generated")) -or $changed

  $markerPath = Join-Path $InstallRoot "install-control-app.marker.json"
  if ((-not (Test-Path -LiteralPath $markerPath)) -or $Force) {
    @{ component = "control-app"; installedAt = (Get-Date).ToString("o") } |
      ConvertTo-Json -Depth 4 |
      Set-Content -LiteralPath $markerPath -Encoding UTF8
    $changed = $true
  }

  $details.markerPath = $markerPath
  New-Result -Success $true -Action "install-control-app" -Changed $changed -Message "Control App directories are installed." -Details $details
} catch {
  New-Result -Success $false -Action "install-control-app" -Changed $false -Message $_.Exception.Message
  exit 1
}
