$ErrorActionPreference = "Stop"

$serverIp = "mc.matstatgaming.com:25566"
$sourceMods = Join-Path $PSScriptRoot "mods"
$minecraftDir = Join-Path $env:APPDATA ".minecraft"
$modsDir = Join-Path $minecraftDir "mods"
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$backupDir = Join-Path $minecraftDir "mods_backup_before_pirate_smp_$timestamp"

Write-Host ""
Write-Host "Pirate SMP - instalacia modov" -ForegroundColor Cyan
Write-Host "================================"
Write-Host ""

if (!(Test-Path -LiteralPath $sourceMods)) {
  Write-Host "Chyba: v tomto priecinku chyba priecinok 'mods'." -ForegroundColor Red
  exit 1
}

$jarFiles = Get-ChildItem -LiteralPath $sourceMods -Filter "*.jar" -File
if ($jarFiles.Count -eq 0) {
  Write-Host "Chyba: v priecinku 'mods' nie su ziadne .jar subory." -ForegroundColor Red
  exit 1
}

if (!(Test-Path -LiteralPath $minecraftDir)) {
  New-Item -ItemType Directory -Force -Path $minecraftDir | Out-Null
}

New-Item -ItemType Directory -Force -Path $modsDir | Out-Null

$oldMods = Get-ChildItem -LiteralPath $modsDir -Filter "*.jar" -File -ErrorAction SilentlyContinue
if ($oldMods.Count -gt 0) {
  New-Item -ItemType Directory -Force -Path $backupDir | Out-Null
  foreach ($oldMod in $oldMods) {
    Move-Item -LiteralPath $oldMod.FullName -Destination (Join-Path $backupDir $oldMod.Name) -Force
  }
  Write-Host "Stare mody boli presunute do zalohy:" -ForegroundColor Yellow
  Write-Host $backupDir
  Write-Host ""
}

foreach ($jar in $jarFiles) {
  Copy-Item -LiteralPath $jar.FullName -Destination (Join-Path $modsDir $jar.Name) -Force
}

Write-Host "Hotovo. Nainstalovane mody:" -ForegroundColor Green
Get-ChildItem -LiteralPath $modsDir -Filter "*.jar" -File | Select-Object -ExpandProperty Name

Write-Host ""
Write-Host "Teraz spusti Minecraft Launcher profil Fabric 1.20.1." -ForegroundColor Cyan
Write-Host "Server IP: $serverIp"
Set-Clipboard -Value $serverIp
Write-Host "IP bola skopirovana do schranky."

$profilesPath = Join-Path $minecraftDir "launcher_profiles.json"
if (Test-Path -LiteralPath $profilesPath) {
  $profilesText = Get-Content -LiteralPath $profilesPath -Raw
  if ($profilesText -notmatch "fabric-loader.*1\.20\.1") {
    Write-Host ""
    Write-Host "Pozor: nenasiel som Fabric 1.20.1 profil v launcheri." -ForegroundColor Yellow
    Write-Host "Ak sa profil nezobrazi, treba nainstalovat Fabric Loader pre Minecraft 1.20.1."
    Write-Host "Otvaram stranku Fabric installeru..."
    Start-Process "https://fabricmc.net/use/installer/"
  }
} else {
  Write-Host ""
  Write-Host "Pozor: Minecraft Launcher este asi nebol spusteny." -ForegroundColor Yellow
  Write-Host "Najprv nech spusti Minecraft Launcher aspon raz."
}
