$ErrorActionPreference = 'Stop'

$repo = Join-Path $env:USERPROFILE 'TibiaPilotNG'
$python = Join-Path $repo '.venv\Scripts\python.exe'
$source = 'D:\Downloads chrome\[KG] Wasps thais 100_ afk.bbot'
$resultPath = 'C:\ProgramData\TibiaPilotNG\wasps-import.json'
$pythonPrefix = Join-Path $repo '.venv\Scripts\python'

if (!(Test-Path -LiteralPath $source)) {
    throw "Wasps profile not found: $source"
}

Stop-ScheduledTask -TaskName 'TibiaPilotNG' -ErrorAction SilentlyContinue
Get-CimInstance Win32_Process | Where-Object {
    $_.ExecutablePath -like "$pythonPrefix*.exe" -and $_.CommandLine -match 'main\.py'
} | ForEach-Object {
    Invoke-CimMethod -InputObject $_ -MethodName Terminate | Out-Null
}

try {
    Set-Location $repo
    $output = & $python 'tools\Apply-BBot-Import.py' $source
    if ($LASTEXITCODE -ne 0) {
        throw 'Wasps profile import failed.'
    }
    $output | Set-Content $resultPath -Encoding utf8
    $output
}
finally {
    Start-ScheduledTask -TaskName 'TibiaPilotNG'
}
