$ErrorActionPreference = 'Stop'

$repo = Join-Path $env:USERPROFILE 'TibiaPilotNG'
$tibiaRoot = Join-Path $env:LOCALAPPDATA 'Tibia'
$logFile = Join-Path $repo '.normal-start.log'
$mutex = [Threading.Mutex]::new($false, 'Local\TibiaPilotNG-OneClick')
$hasMutex = $false

try {
    Stop-ScheduledTask -TaskName 'TibiaPilotNG-OneClick' -ErrorAction SilentlyContinue
    Start-Sleep -Milliseconds 500
    try {
        $hasMutex = $mutex.WaitOne(10000)
    } catch [Threading.AbandonedMutexException] {
        $hasMutex = $true
    }
    if (!$hasMutex) { throw 'Der Bot-Modus konnte nicht beendet werden.' }

    & (Join-Path $repo 'tools\Stop-TibiaPilotNG.ps1')
    for ($attempt = 0; $attempt -lt 20; $attempt++) {
        $remaining = @(Get-CimInstance Win32_Process | Where-Object {
            $_.ExecutablePath -like "$tibiaRoot\*"
        })
        if ($remaining.Count -eq 0) { break }
        $remaining | ForEach-Object {
            & taskkill.exe /PID $_.ProcessId /T /F | Out-Null
        }
        Start-Sleep -Milliseconds 500
    }
    $remaining = @(Get-CimInstance Win32_Process | Where-Object {
        $_.ExecutablePath -like "$tibiaRoot\*"
    })
    if ($remaining.Count -gt 0) { throw 'Tibia konnte nicht sauber beendet werden.' }
    & (Join-Path $repo 'tools\Set-TibiaProfile.ps1') -Profile normal | Out-Null
    & (Join-Path $repo '.venv\Scripts\python.exe') `
        (Join-Path $repo 'tools\Restore-Bot-Display.py') | Out-Null
    & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass `
        -File (Join-Path $repo 'tools\Restart-Tibia-Client.ps1')
    if ($LASTEXITCODE -ne 0) { throw 'Tibia konnte nicht gestartet werden.' }
    "$(Get-Date -Format o) normal-running" | Add-Content $logFile -Encoding UTF8
}
catch {
    "$(Get-Date -Format o) error=$($_.Exception.Message)" | Add-Content $logFile -Encoding UTF8
}
finally {
    if ($hasMutex) { $mutex.ReleaseMutex() }
    $mutex.Dispose()
}
