param(
    [Parameter(Mandatory)]
    [ValidateSet('bot', 'normal')]
    [string]$Profile
)

$ErrorActionPreference = 'Stop'

$tibiaRoot = Join-Path $env:LOCALAPPDATA 'Tibia'
$liveOptions = Join-Path $tibiaRoot 'packages\Tibia\conf\clientoptions.json'
$liveCharacters = Join-Path $tibiaRoot 'packages\Tibia\characterdata'
$root = Join-Path $env:LOCALAPPDATA 'TibiaPilotNG'
$profiles = Join-Path $root 'profiles'
$marker = Join-Path $root 'active-profile.txt'
$targetRoot = Join-Path $profiles $Profile
$targetOptions = Join-Path $targetRoot 'clientoptions.json'
$targetCharacters = Join-Path $targetRoot 'characterdata'

if (!(Test-Path $liveOptions)) { throw 'Tibia clientoptions.json was not found.' }
if (!(Test-Path $liveCharacters)) { throw 'Tibia characterdata was not found.' }
if (Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -like "$tibiaRoot\*" }) {
    throw 'Close Tibia before switching its profile.'
}

function Sync-Directory([string]$Source, [string]$Destination) {
    New-Item $Destination -ItemType Directory -Force | Out-Null
    & robocopy.exe $Source $Destination /MIR /COPY:DAT /DCOPY:DAT /R:2 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Null
    if ($LASTEXITCODE -ge 8) { throw "Could not sync $Source to $Destination." }
}

New-Item $targetRoot -ItemType Directory -Force | Out-Null
$active = if (Test-Path $marker) { (Get-Content $marker -Raw).Trim() } else { 'normal' }
$activeRoot = Join-Path $profiles $active
$activeOptions = Join-Path $activeRoot 'clientoptions.json'
$activeCharacters = Join-Path $activeRoot 'characterdata'
if ($active -ne $Profile) {
    New-Item $activeRoot -ItemType Directory -Force | Out-Null
    Copy-Item $liveOptions $activeOptions -Force
    Sync-Directory $liveCharacters $activeCharacters
}
if (!(Test-Path $targetOptions)) { Copy-Item $liveOptions $targetOptions -Force }
if (!(Test-Path $targetCharacters)) { Sync-Directory $liveCharacters $targetCharacters }
Copy-Item $targetOptions $liveOptions -Force
Sync-Directory $targetCharacters $liveCharacters
Set-Content $marker $Profile -Encoding ascii
Write-Output "profile=$Profile"
