[CmdletBinding(SupportsShouldProcess = $true)]
# Winlogon DefaultPassword is plaintext by design; clinic config also stores it as a string.
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
    'PSAvoidUsingPlainTextForPassword',
    '',
    Justification = 'Autologon writes DefaultPassword to Winlogon registry as plain text.'
)]
param(
    [string]$SourcePath = $PSScriptRoot,
    [string]$EmmaBase = 'C:\Emma',
    [string]$EmmaHome = 'C:\Emma\current',
    [string]$AutologonUser = 'Emma',
    [string]$AutologonPassword = 'emmaPass123',
    [string]$ConfigPath = $null,
    [switch]$SkipReboot
)

$ErrorActionPreference = 'Stop'

if (-not $ConfigPath) {
    $usbConfig = Join-Path $SourcePath 'EmmaClinic.config.json'
    $repoConfig = Join-Path (Split-Path $SourcePath -Parent) 'config\EmmaClinic.config.json'
    $releaseConfig = Join-Path $SourcePath 'config.json'
    if (Test-Path $usbConfig) { $ConfigPath = $usbConfig }
    elseif (Test-Path $releaseConfig) { $ConfigPath = $releaseConfig }
    elseif (Test-Path $repoConfig) { $ConfigPath = $repoConfig }
}

if ($ConfigPath -and (Test-Path $ConfigPath)) {
    $cfg = Get-Content $ConfigPath -Raw | ConvertFrom-Json
    if ($cfg.installPath) { $EmmaHome = $cfg.installPath }
    if ($cfg.autologonUser) { $AutologonUser = $cfg.autologonUser }
    if ($cfg.autologonPassword) { $AutologonPassword = $cfg.autologonPassword }
}

$releaseRoot = $SourcePath
if (Test-Path (Join-Path $SourcePath 'runtime\emma-agent.exe')) {
    $releaseRoot = $SourcePath
}
elseif (Test-Path (Join-Path (Split-Path $SourcePath -Parent) 'runtime\emma-agent.exe')) {
    $releaseRoot = Split-Path $SourcePath -Parent
}

Write-Host "Installiere Emma Local nach $EmmaHome"

New-Item -ItemType Directory -Force -Path $EmmaBase | Out-Null
if (Test-Path $EmmaHome) {
    Remove-Item -Path $EmmaHome -Recurse -Force
}
New-Item -ItemType Directory -Force -Path $EmmaHome | Out-Null

Copy-Item -Path (Join-Path $releaseRoot '*') -Destination $EmmaHome -Recurse -Force

$winlogonPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
if ($PSCmdlet.ShouldProcess($winlogonPath, 'Configure autologon')) {
    if (-not (Test-Path $winlogonPath)) { New-Item -Path $winlogonPath -Force | Out-Null }
    Set-ItemProperty -Path $winlogonPath -Name 'AutoAdminLogon' -Value '1'
    Set-ItemProperty -Path $winlogonPath -Name 'DefaultUserName' -Value $AutologonUser
    Set-ItemProperty -Path $winlogonPath -Name 'DefaultPassword' -Value $AutologonPassword
    Remove-ItemProperty -Path $winlogonPath -Name 'AutoLogonCount' -ErrorAction SilentlyContinue
    Set-ItemProperty -Path $winlogonPath -Name 'Shell' -Value 'explorer.exe' -Type String
    Set-ItemProperty -Path $winlogonPath -Name 'AutoRestartShell' -Value 1 -Type DWord
}

$displayScript = Join-Path $EmmaHome 'provisioning\Emma-Display.ps1'
if (Test-Path $displayScript) {
    . $displayScript
    Set-EmmaKioskDisplay -ScriptDir (Join-Path $EmmaHome 'provisioning')
}

$firewallScript = Join-Path $EmmaHome 'provisioning\Emma-Firewall.ps1'
if (Test-Path $firewallScript) {
    . $firewallScript
    Update-EmmaLocalFirewallRules -Port 3000 -AgentExe (Join-Path $EmmaHome 'runtime\emma-agent.exe')
}

$registerScript = Join-Path $EmmaHome 'provisioning\Register-EmmaService.ps1'
if (-not (Test-Path $registerScript)) {
    throw "Register-EmmaService.ps1 nicht gefunden"
}
& $registerScript -EmmaHome $EmmaHome

$kioskScript = Join-Path $EmmaHome 'provisioning\Start-EmmaKiosk.ps1'
$agentExe = Join-Path $EmmaHome 'runtime\emma-agent.exe'

$logonAction = New-ScheduledTaskAction -Execute 'powershell.exe' `
    -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$kioskScript`""
$logonTrigger = New-ScheduledTaskTrigger -AtLogOn -User $AutologonUser
$logonPrincipal = New-ScheduledTaskPrincipal -UserId $AutologonUser -LogonType Interactive -RunLevel Highest
$logonSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
    -ExecutionTimeLimit ([TimeSpan]::Zero)

Register-ScheduledTask -TaskName 'Emma Local Kiosk' -Action $logonAction -Trigger $logonTrigger `
    -Principal $logonPrincipal -Settings $logonSettings -Force | Out-Null

if (Test-Path $agentExe) {
    $watchdogAction = New-ScheduledTaskAction -Execute $agentExe -Argument 'watchdog'
    Register-ScheduledTask -TaskName 'Emma Local Watchdog' -Action $watchdogAction -Trigger $logonTrigger `
        -Principal $logonPrincipal -Settings $logonSettings -Force | Out-Null
}

$updateScript = Join-Path $EmmaHome 'provisioning\Run-EmmaUpdate.ps1'
if (Test-Path $updateScript) {
    $updateAction = New-ScheduledTaskAction -Execute 'powershell.exe' `
        -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$updateScript`""
    $updateTrigger = New-ScheduledTaskTrigger -Daily -At '03:00'
    Register-ScheduledTask -TaskName 'Emma Local Update' -Action $updateAction -Trigger $updateTrigger `
        -Principal $logonPrincipal -Settings $logonSettings -Force | Out-Null
}

Write-Host 'Emma Local Installation abgeschlossen. Bitte neu starten.'
if (-not $SkipReboot -and $PSCmdlet.ShouldProcess('localhost', 'Restart after install')) {
    Restart-Computer -Force
}
elseif ($SkipReboot) {
    Write-Host 'Reboot skipped (-SkipReboot).'
}
