param(
    [string]$GamePath = "",
    [string]$Feed = $(if ($env:STARDEW_MODSYNC_FEED) { $env:STARDEW_MODSYNC_FEED } else { "https://stardew.thetorg.org/" })
)

$ErrorActionPreference = "Stop"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
if (-not $GamePath) {
    $Candidates = @()
    if (${env:ProgramFiles(x86)}) { $Candidates += Join-Path ${env:ProgramFiles(x86)} "Steam\steamapps\common\Stardew Valley" }
    if ($env:ProgramFiles) { $Candidates += Join-Path $env:ProgramFiles "Steam\steamapps\common\Stardew Valley" }
    $GamePath = $Candidates | Where-Object { Test-Path -LiteralPath (Join-Path $_ "Stardew Valley.dll") } | Select-Object -First 1
}
if (-not $GamePath -or -not (Test-Path -LiteralPath (Join-Path $GamePath "Stardew Valley.dll"))) {
    throw "Stardew Valley was not found. Re-run install.ps1 -GamePath 'C:\path\to\Stardew Valley'."
}

$OfficialInstaller = Join-Path $ScriptDir "official\windows\SMAPI.Installer.exe"
$OfficialData = Join-Path $ScriptDir "official\windows\install.dat"
$ClientPayload = Join-Path $ScriptDir "payload\client"
if (-not (Test-Path -LiteralPath $OfficialInstaller) -or -not (Test-Path -LiteralPath $OfficialData)) {
    throw "The bundled official SMAPI Windows installer is incomplete."
}
foreach ($Required in @(
    (Join-Path $ClientPayload "windows\Sync-StardewMods.ps1"),
    (Join-Path $ScriptDir "payload\compat-launch.ps1")
)) {
    if (-not (Test-Path -LiteralPath $Required -PathType Leaf)) { throw "Installer payload is incomplete: $Required" }
}

Write-Host "Installing official SMAPI..."
& $OfficialInstaller --install --no-prompt --game-path $GamePath
if ($LASTEXITCODE -ne 0) { throw "The official SMAPI installer failed with exit code $LASTEXITCODE." }

$ClientDir = Join-Path $GamePath ".stardew-modsync"
$PendingClient = Join-Path $GamePath (".stardew-modsync.new." + [Guid]::NewGuid().ToString("N"))
Copy-Item -Recurse -Force -LiteralPath $ClientPayload -Destination $PendingClient
if (Test-Path -LiteralPath $ClientDir) { Remove-Item -Recurse -Force -LiteralPath $ClientDir }
Move-Item -LiteralPath $PendingClient -Destination $ClientDir

# Keep existing Steam launch options working by replacing the compatibility
# script at the same path used by the previous installer generation.
$LegacyState = Join-Path $GamePath ".thors-fjord"
New-Item -ItemType Directory -Force -Path $LegacyState | Out-Null
Copy-Item -Force -LiteralPath (Join-Path $ScriptDir "payload\compat-launch.ps1") -Destination (Join-Path $LegacyState "launch.ps1")

$ShortcutPath = Join-Path ([Environment]::GetFolderPath("Desktop")) "Thor's Fjord.lnk"
$Shell = New-Object -ComObject WScript.Shell
$Shortcut = $Shell.CreateShortcut($ShortcutPath)
$Shortcut.TargetPath = "powershell.exe"
$Shortcut.Arguments = '-NoProfile -ExecutionPolicy Bypass -File "' + (Join-Path $LegacyState "launch.ps1") + '" -GamePath "' + $GamePath + '"'
$Shortcut.WorkingDirectory = $GamePath
$Shortcut.Description = "Launch Thor's Fjord with managed mod updates"
$Shortcut.Save()

Write-Host "Synchronizing the managed mod pack..."
try {
    & (Join-Path $ClientDir "windows\Sync-StardewMods.ps1") -GamePath $GamePath -Feed $Feed -NoLaunch
} catch {
    $ErrorLog = Join-Path $ClientDir "last-error.log"
    @(
        "Thor's Fjord initial sync failed at $(Get-Date -Format o)",
        $_.Exception.ToString(),
        $_.ScriptStackTrace
    ) | Set-Content -Encoding UTF8 -LiteralPath $ErrorLog
    Write-Host "Initial mod sync failed: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "Details were saved to: $ErrorLog" -ForegroundColor Yellow
    throw
}

$SteamOption = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "' + (Join-Path $LegacyState "launch.ps1") + '" -GamePath "' + $GamePath + '" %command%'
Write-Host ""
Write-Host "Thor's Fjord is installed." -ForegroundColor Green
Write-Host "Existing Thor's Fjord Steam launch options continue to work. If needed, set:"
Write-Host $SteamOption
