[CmdletBinding()]
param(
  [string]$PackageRoot = "",
  [string]$InstallDir = "$env:LOCALAPPDATA\Programs\regen-mde"
)

$ErrorActionPreference = "Stop"

if ([string]::IsNullOrWhiteSpace($PackageRoot)) {
  $PackageApp = Join-Path $PSScriptRoot "app"
  if (Test-Path -LiteralPath (Join-Path $PackageApp "BuildCorpusEditor.exe")) {
    $PackageRoot = $PackageApp
  } else {
    $PackageRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
  }
}

$ProductName = "regen-mde"
$LegacyProductNames = @("Manuscript Forge", "Regen.MDeditor")
$AppSource = if (Test-Path -LiteralPath (Join-Path $PackageRoot "BuildCorpusEditor.exe")) {
  $PackageRoot
} else {
  Join-Path $PackageRoot "dist\windows-editor"
}
$AppExe = Join-Path $AppSource "BuildCorpusEditor.exe"
$StartMenuDir = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\LIFE AI"
$ShortcutPath = Join-Path $StartMenuDir "$ProductName.lnk"
$UninstallShortcutPath = Join-Path $StartMenuDir "Uninstall $ProductName.lnk"
$LegacyInstallDir = Join-Path $env:LOCALAPPDATA "Programs\Manuscript Forge"
$LegacyInstallDir2 = Join-Path $env:LOCALAPPDATA "Programs\Regen.MDeditor"

if (-not (Test-Path -LiteralPath $AppExe)) {
  throw "Package is missing BuildCorpusEditor.exe"
}

function Remove-FileVerb {
  param(
    [string]$Extension,
    [string]$Verb
  )
  Remove-Item -LiteralPath "Registry::HKEY_CURRENT_USER\Software\Classes\SystemFileAssociations\$Extension\shell\$Verb" -Recurse -Force -ErrorAction SilentlyContinue
}

Get-Process BuildCorpusEditor -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
foreach ($legacyProductName in $LegacyProductNames) {
  Remove-Item -LiteralPath (Join-Path $StartMenuDir "$legacyProductName.lnk") -Force -ErrorAction SilentlyContinue
  Remove-Item -LiteralPath (Join-Path $StartMenuDir "Uninstall $legacyProductName.lnk") -Force -ErrorAction SilentlyContinue
}
Remove-Item -LiteralPath $ShortcutPath -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath $UninstallShortcutPath -Force -ErrorAction SilentlyContinue
foreach ($ext in @(".md", ".docx", ".pptx", ".ppt")) {
  foreach ($verb in @("ManuscriptForgeOpen", "BuildCorpusOpenEditor", "RegenMDEditorOpen", "BuildCorpusToMarkdown", "BuildCorpusToWord", "BuildCorpusInlineImages")) {
    Remove-FileVerb -Extension $ext -Verb $verb
  }
}
Remove-Item -LiteralPath "Registry::HKEY_CURRENT_USER\Software\Classes\Directory\shell\BuildCorpusFolderToMarkdown" -Recurse -Force -ErrorAction SilentlyContinue
if ((Test-Path -LiteralPath $LegacyInstallDir) -and ($LegacyInstallDir -ne $InstallDir)) {
  Remove-Item -LiteralPath $LegacyInstallDir -Recurse -Force -ErrorAction SilentlyContinue
}
if ((Test-Path -LiteralPath $LegacyInstallDir2) -and ($LegacyInstallDir2 -ne $InstallDir)) {
  Remove-Item -LiteralPath $LegacyInstallDir2 -Recurse -Force -ErrorAction SilentlyContinue
}

New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
foreach ($item in @("wwwroot", "runtimes")) {
  Remove-Item -LiteralPath (Join-Path $InstallDir $item) -Recurse -Force -ErrorAction SilentlyContinue
}
foreach ($pattern in @("BuildCorpusEditor.*", "Microsoft.Web.WebView2.*", "WebView2Loader.dll")) {
  Get-ChildItem -LiteralPath $InstallDir -Filter $pattern -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
}
Copy-Item -Path (Join-Path $AppSource "*") -Destination $InstallDir -Recurse -Force
foreach ($item in @("bin", "src")) {
  $sourcePath = Join-Path $PackageRoot $item
  if (Test-Path -LiteralPath $sourcePath) {
    $destinationPath = Join-Path $InstallDir $item
    Remove-Item -LiteralPath $destinationPath -Recurse -Force -ErrorAction SilentlyContinue
    Copy-Item -LiteralPath $sourcePath -Destination $InstallDir -Recurse -Force
  }
}
foreach ($item in @("requirements.txt", "package.json", "package-lock.json")) {
  $sourcePath = Join-Path $PackageRoot $item
  if (Test-Path -LiteralPath $sourcePath) {
    Copy-Item -LiteralPath $sourcePath -Destination $InstallDir -Force
  }
}

$InstalledExe = Join-Path $InstallDir "BuildCorpusEditor.exe"
$UninstallScript = Join-Path $InstallDir "uninstall-regen-mde.ps1"

if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
  throw "Node.js is required on PATH for DOCX/Markdown conversion."
}
$NodeExe = (Get-Command node -ErrorAction Stop).Source

$requirements = Join-Path $InstallDir "requirements.txt"
$pythonReady = $false
foreach ($candidate in @("py", "python")) {
  if (-not (Get-Command $candidate -ErrorAction SilentlyContinue)) { continue }
  if ($candidate -eq "py") {
    & py -3 -c "import omml2latex, boto3, PIL, docx" 2>$null
  } else {
    & python -c "import omml2latex, boto3, PIL, docx" 2>$null
  }
  if ($LASTEXITCODE -eq 0) {
    $pythonReady = $true
    break
  }
}

if (-not $pythonReady) {
  Write-Warning "Python conversion dependencies are not already installed. Install them later with: py -3 -m pip install -r `"$requirements`""
}

New-Item -ItemType Directory -Force -Path $StartMenuDir | Out-Null
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut($ShortcutPath)
$shortcut.TargetPath = $InstalledExe
$shortcut.WorkingDirectory = $InstallDir
$shortcut.IconLocation = "$InstalledExe,0"
$shortcut.Description = "$ProductName Word and Markdown editor"
$shortcut.Save()

function Set-FileVerb {
  param(
    [string]$Extension,
    [string]$Verb,
    [string]$Label,
    [string]$Command
  )
  $key = "Registry::HKEY_CURRENT_USER\Software\Classes\SystemFileAssociations\$Extension\shell\$Verb"
  $commandKey = Join-Path $key "command"
  New-Item -Path $commandKey -Force | Out-Null
  New-ItemProperty -Path $key -Name "MUIVerb" -Value $Label -PropertyType String -Force | Out-Null
  New-ItemProperty -Path $key -Name "Icon" -Value $InstalledExe -PropertyType ExpandString -Force | Out-Null
  [Microsoft.Win32.Registry]::SetValue(
    "HKEY_CURRENT_USER\Software\Classes\SystemFileAssociations\$Extension\shell\$Verb\command",
    "",
    $Command,
    [Microsoft.Win32.RegistryValueKind]::String)
}

function Set-FolderVerb {
  param(
    [string]$Verb,
    [string]$Label,
    [string]$Command
  )
  $key = "Registry::HKEY_CURRENT_USER\Software\Classes\Directory\shell\$Verb"
  $commandKey = Join-Path $key "command"
  New-Item -Path $commandKey -Force | Out-Null
  New-ItemProperty -Path $key -Name "MUIVerb" -Value $Label -PropertyType String -Force | Out-Null
  New-ItemProperty -Path $key -Name "Icon" -Value $InstalledExe -PropertyType ExpandString -Force | Out-Null
  [Microsoft.Win32.Registry]::SetValue(
    "HKEY_CURRENT_USER\Software\Classes\Directory\shell\$Verb\command",
    "",
    $Command,
    [Microsoft.Win32.RegistryValueKind]::String)
}

Set-FileVerb -Extension ".md" -Verb "RegenMDEditorOpen" -Label "Open in regen-mde" -Command "`"$InstalledExe`" `"%1`""
Set-FileVerb -Extension ".docx" -Verb "RegenMDEditorOpen" -Label "Open in regen-mde" -Command "`"$InstalledExe`" `"%1`""
Set-FileVerb -Extension ".docx" -Verb "BuildCorpusToMarkdown" -Label "Convert to Markdown" -Command "`"$NodeExe`" `"$InstallDir\bin\build-corpus.js`" `"%1`" --out-same-dir"
Set-FileVerb -Extension ".pptx" -Verb "BuildCorpusToMarkdown" -Label "Convert to Markdown" -Command "`"$NodeExe`" `"$InstallDir\bin\build-corpus.js`" `"%1`" --out-same-dir"
Set-FileVerb -Extension ".ppt" -Verb "BuildCorpusToMarkdown" -Label "Convert to Markdown" -Command "`"$NodeExe`" `"$InstallDir\bin\build-corpus.js`" `"%1`" --out-same-dir"
Set-FileVerb -Extension ".md" -Verb "BuildCorpusToWord" -Label "Convert to Word" -Command "`"$NodeExe`" `"$InstallDir\bin\build-corpus.js`" `"%1`" --to word --out-same-dir"
Set-FileVerb -Extension ".md" -Verb "BuildCorpusInlineImages" -Label "Inline Markdown Images" -Command "`"$NodeExe`" `"$InstallDir\bin\build-corpus.js`" `"%1`" --inline-images"
Set-FolderVerb -Verb "BuildCorpusFolderToMarkdown" -Label "Convert Documents to Markdown" -Command "`"$NodeExe`" `"$InstallDir\bin\build-corpus.js`" `"%V`" --out-same-dir"
New-Item -Path "Registry::HKEY_CURRENT_USER\Software\Classes\.md\ShellNew" -Force | Out-Null
New-ItemProperty -Path "Registry::HKEY_CURRENT_USER\Software\Classes\.md" -Name "Content Type" -Value "text/markdown" -PropertyType String -Force | Out-Null
New-ItemProperty -Path "Registry::HKEY_CURRENT_USER\Software\Classes\.md\ShellNew" -Name "NullFile" -Value "" -PropertyType String -Force | Out-Null

$uninstall = @"
`$ErrorActionPreference = "Stop"
`$ProductName = "regen-mde"
`$InstallDir = Split-Path -Parent `$MyInvocation.MyCommand.Path
`$StartMenuDir = Join-Path `$env:APPDATA "Microsoft\Windows\Start Menu\Programs\LIFE AI"
Get-Process BuildCorpusEditor -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath (Join-Path `$StartMenuDir "`$ProductName.lnk") -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath (Join-Path `$StartMenuDir "Uninstall `$ProductName.lnk") -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath (Join-Path `$StartMenuDir "Regen.MDeditor.lnk") -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath (Join-Path `$StartMenuDir "Manuscript Forge.lnk") -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath (Join-Path `$StartMenuDir "Uninstall Regen.MDeditor.lnk") -Force -ErrorAction SilentlyContinue
foreach (`$ext in @(".md", ".docx", ".pptx", ".ppt")) {
  foreach (`$verb in @("RegenMDEditorOpen", "BuildCorpusToMarkdown", "BuildCorpusToWord", "BuildCorpusInlineImages", "ManuscriptForgeOpen", "BuildCorpusOpenEditor")) {
    Remove-Item -LiteralPath "Registry::HKEY_CURRENT_USER\Software\Classes\SystemFileAssociations\`$ext\shell\`$verb" -Recurse -Force -ErrorAction SilentlyContinue
  }
}
Remove-Item -LiteralPath "Registry::HKEY_CURRENT_USER\Software\Classes\Directory\shell\BuildCorpusFolderToMarkdown" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath "Registry::HKEY_CURRENT_USER\Software\Classes\.md\ShellNew" -Recurse -Force -ErrorAction SilentlyContinue
for (`$i = 0; `$i -lt 10; `$i++) {
  Start-Sleep -Milliseconds 250
  try {
    Remove-Item -LiteralPath `$InstallDir -Recurse -Force
    break
  } catch {
    if (`$i -eq 9) { throw }
  }
}
Write-Host "`$ProductName removed."
"@
Set-Content -LiteralPath $UninstallScript -Value $uninstall -Encoding UTF8

$uninstallShortcut = $shell.CreateShortcut($UninstallShortcutPath)
$uninstallShortcut.TargetPath = "powershell.exe"
$uninstallShortcut.Arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$UninstallScript`""
$uninstallShortcut.WorkingDirectory = $InstallDir
$uninstallShortcut.IconLocation = "$InstalledExe,0"
$uninstallShortcut.Description = "Uninstall $ProductName"
$uninstallShortcut.Save()

Write-Host "$ProductName installed."
Write-Host "InstallDir=$InstallDir"
Write-Host "Shortcut=$ShortcutPath"
Write-Host "Executable=$InstalledExe"
