<#
.SYNOPSIS
  Apply Homestead V3 Family Hotfix v5 (NeoForge 1.21.1).

.DESCRIPTION
  Drops 6 new mod jars into your Minecraft mods folder, after backing up
  the current mods. Run this on each family member's PC.

  These mods MUST match the server -- after v5 goes live you cannot join
  Homestead until you run this.

  New in v5:
    - Block Pops          (collectible Funko-style figures)
    - Size Shifting Potions + Pehkui  (mushroom grow/shrink potions)
    - Create Jetpack      (backtank-powered jetpack)
    - Twigs               (stone mosaics / bricks for builds)
    (+ GeckoLib, a required library for Block Pops)
    NOTE: Chisels & Bits ("the pixel mod") is coming in a later update.

  Auto-detects common launcher instance paths (CurseForge, Prism, Modrinth
  App, ATLauncher). Override with -ModsFolder if your install is elsewhere.

.EXAMPLE
  .\Apply-FamilyHotfix-v5.ps1
  .\Apply-FamilyHotfix-v5.ps1 -ModsFolder "D:\Games\MC\Homestead\mods"
  .\Apply-FamilyHotfix-v5.ps1 -Force
#>
[CmdletBinding()]
param(
    [string]$ModsFolder,
    [switch]$Force
)

$ErrorActionPreference = 'Stop'
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$jarSource = Join-Path $scriptDir 'mods-add'

# ---- Expected jars + sha256 (verified at build time) ----
$expected = @{
    'geckolib-neoforge-1.21.1-4.8.4.jar'         = 'a1b6ce25e8627aa7e748672eedb6b71af68e0993462313649c259f38e42bcac9'
    'BlockPops-Neoforge-1.21.1-1.5.0.jar'        = '9b0a66fb79ecde58a6ee32a3dc7852a70f9149c0b454e8f1670a03474f3b6a76'
    'SizeShiftingPotions-neoforge-1.8.0+1.21.jar'= 'a15ff0dea61592d1dc42ea728453df5c629aaba2531e1dd3854bc30d917ba205'
    'Pehkui-3.8.3+1.21-neoforge.jar'             = '50aab835b0f98dedf33383483b021789c2991786f02b00e6d1b7152dc43570ec'
    'create_jetpack-forge-5.1.2.jar'             = '9fe5a681ea841ce9dc02e7132cd360e1c3e75314905b4ef1493e7548265d0985'
    'Twigs-1.21.1-3.1.2.jar'                     = '794dfad0c38b33f9b580a8205e72e8b2004ddb5e0bce398735c2b775cbf5cd77'
}

function Write-Step($msg) { Write-Host "==> $msg" -ForegroundColor Cyan }
function Write-Ok  ($msg) { Write-Host "    [OK] $msg" -ForegroundColor Green }
function Write-Warn($msg) { Write-Host "    [!]  $msg" -ForegroundColor Yellow }
function Write-Err ($msg) { Write-Host "    [X]  $msg" -ForegroundColor Red }

# ---- 0. Verify the bundled jars exist and match hashes ----
Write-Step "Verifying bundled mod jars"
if (-not (Test-Path $jarSource)) {
    Write-Err "Jar source folder missing: $jarSource"
    Write-Err "Make sure you extracted the ENTIRE hotfix zip -- not just this script."
    exit 1
}
$verifyFailed = $false
foreach ($name in $expected.Keys) {
    $path = Join-Path $jarSource $name
    if (-not (Test-Path $path)) { Write-Err "Missing: $name"; $verifyFailed = $true; continue }
    $hash = (Get-FileHash -Algorithm SHA256 -Path $path).Hash.ToLower()
    if ($hash -ne $expected[$name]) { Write-Err "Hash mismatch for $name (got $hash)"; $verifyFailed = $true }
    else { Write-Ok $name }
}
if ($verifyFailed) { Write-Err "Bundle integrity check failed. Re-download the hotfix zip."; exit 1 }

# ---- 1. Find the mods folder ----
Write-Step "Locating Minecraft mods folder"
if ($ModsFolder) {
    if (-not (Test-Path $ModsFolder)) { Write-Err "Specified -ModsFolder does not exist: $ModsFolder"; exit 1 }
    Write-Ok "Using -ModsFolder override: $ModsFolder"
} else {
    $candidates = New-Object System.Collections.Generic.List[string]
    $cfRoot = Join-Path $env:USERPROFILE 'curseforge\minecraft\Instances'
    if (Test-Path $cfRoot) { Get-ChildItem -Path $cfRoot -Directory -ErrorAction SilentlyContinue | ForEach-Object {
        $m = Join-Path $_.FullName 'mods'; if (Test-Path $m) { $candidates.Add($m) } } }
    $prismRoot = Join-Path $env:APPDATA 'PrismLauncher\instances'
    if (Test-Path $prismRoot) { Get-ChildItem -Path $prismRoot -Directory -ErrorAction SilentlyContinue | ForEach-Object {
        $m = Join-Path $_.FullName '.minecraft\mods'; if (Test-Path $m) { $candidates.Add($m) } } }
    $mrRoot = Join-Path $env:APPDATA 'com.modrinth.theseus\profiles'
    if (Test-Path $mrRoot) { Get-ChildItem -Path $mrRoot -Directory -ErrorAction SilentlyContinue | ForEach-Object {
        $m = Join-Path $_.FullName 'mods'; if (Test-Path $m) { $candidates.Add($m) } } }
    $atRoot = Join-Path $env:USERPROFILE 'ATLauncher\instances'
    if (Test-Path $atRoot) { Get-ChildItem -Path $atRoot -Directory -ErrorAction SilentlyContinue | ForEach-Object {
        $m = Join-Path $_.FullName 'mods'; if (Test-Path $m) { $candidates.Add($m) } } }
    # Vanilla launcher fallback
    $vanilla = Join-Path $env:APPDATA '.minecraft\mods'
    if (Test-Path $vanilla) { $candidates.Add($vanilla) }

    if ($candidates.Count -eq 0) {
        Write-Err "No mods folders found in standard launcher locations."
        Write-Err "Pass -ModsFolder C:\path\to\mods to specify manually."; exit 1
    }
    $scored = foreach ($c in $candidates) {
        $score = 0
        if ($c -match 'homestead') { $score += 100 }
        if ($c -match 'vanilla')   { $score += 40 }
        $jarCount = (Get-ChildItem -Path $c -Filter *.jar -ErrorAction SilentlyContinue).Count
        # boost instances that already look like the V3 pack
        if (Get-ChildItem -Path $c -Filter 'create-1.21.1-*.jar' -ErrorAction SilentlyContinue) { $score += 80 }
        $score += [Math]::Min($jarCount, 50)
        [PSCustomObject]@{ Path = $c; Score = $score; Jars = $jarCount }
    }
    $scored = $scored | Sort-Object -Property Score -Descending
    if ($scored[0].Score -lt 80) {
        Write-Warn "Couldn't confidently find the Homestead instance. Found these:"
        $scored | ForEach-Object { Write-Host ("        [{0:D3} jars] {1}" -f $_.Jars, $_.Path) }
        Write-Err "Re-run with -ModsFolder to pick the right one."; exit 1
    }
    $ModsFolder = $scored[0].Path
    Write-Ok "Found Homestead instance: $ModsFolder"
    Write-Ok "Current mod count: $($scored[0].Jars)"
    $alts = $scored | Where-Object { $_.Path -ne $ModsFolder }
    if ($alts) { Write-Warn "Other instances exist (use -ModsFolder to switch):"; $alts | ForEach-Object { Write-Host "        $($_.Path)" } }
}

# ---- 2. Confirm ----
if (-not $Force) {
    Write-Host ""
    Write-Host "Will copy 6 new mod jars to:" -ForegroundColor White
    Write-Host "  $ModsFolder" -ForegroundColor White
    Write-Host "(Existing mods are backed up first.)" -ForegroundColor Gray
    Write-Host ""
    $resp = Read-Host "Proceed? [y/N]"
    if ($resp -notmatch '^[yY]') { Write-Host "Aborted." -ForegroundColor Yellow; exit 0 }
}

# ---- 3. Backup ----
Write-Step "Backing up current mods folder"
$instanceRoot = Split-Path -Parent $ModsFolder
$backupRoot   = Join-Path $instanceRoot 'mods-backups'
if (-not (Test-Path $backupRoot)) { New-Item -ItemType Directory -Path $backupRoot | Out-Null }
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$backupDir = Join-Path $backupRoot "pre-v5-$stamp"
Copy-Item -Path $ModsFolder -Destination $backupDir -Recurse
Write-Ok "Backed up $((Get-ChildItem -Path $backupDir -Filter *.jar).Count) jars to: $backupDir"

# ---- 4. Remove older versions of these mods (if present) ----
Write-Step "Removing older versions of the new mods (if any)"
$prefixes = @('geckolib','BlockPops','SizeShiftingPotions','Pehkui','create_jetpack','Twigs')
$removed = 0
foreach ($prefix in $prefixes) {
    Get-ChildItem -Path $ModsFolder -Filter "$prefix*.jar" -ErrorAction SilentlyContinue | ForEach-Object {
        if (-not $expected.ContainsKey($_.Name)) {
            Remove-Item -Path $_.FullName -Force; Write-Warn "Removed older: $($_.Name)"; $script:removed++
        }
    }
}
if ($removed -eq 0) { Write-Ok "No older versions found." }

# ---- 5. Copy new jars ----
Write-Step "Copying new jars"
$copied = 0; $skipped = 0
foreach ($name in $expected.Keys) {
    $dst = Join-Path $ModsFolder $name
    if (Test-Path $dst) {
        $h = (Get-FileHash -Algorithm SHA256 -Path $dst).Hash.ToLower()
        if ($h -eq $expected[$name]) { Write-Ok "Already present: $name"; $skipped++; continue }
    }
    Copy-Item -Path (Join-Path $jarSource $name) -Destination $dst -Force
    Write-Ok "Copied: $name"; $copied++
}

# ---- 6. Done ----
Write-Host ""
Write-Step "Done"
Write-Host "  Copied:  $copied" -ForegroundColor Green
Write-Host "  Skipped: $skipped (already up to date)" -ForegroundColor Gray
Write-Host "  Removed: $removed older versions" -ForegroundColor Gray
Write-Host "  Backup:  $backupDir" -ForegroundColor Gray
Write-Host ""
Write-Host "Restart your Minecraft launcher and reconnect to homestead.fritzytech.com (44.220.107.36)." -ForegroundColor White
Write-Host "If the game crashes on load, restore by copying jars back from the backup folder." -ForegroundColor Gray
