$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Windows.Forms
. (Join-Path $PSScriptRoot 'Common.ps1')
. (Join-Path $PSScriptRoot 'UIHelpers.ps1')
Initialize-RBWindowsUI

try {
    $state = Get-RBConfiguration
    $en = (Get-RBLanguage $state) -eq 'en'
    $result = Invoke-RestMethod -Method Get -Uri "$($state.Config.gateway)/api/v1/restore-requests" -Headers (Get-RBBasicHeader $state) -TimeoutSec 30
    $approved = @($result.restore_requests | Where-Object { $_.status -eq 'approved' })
    if (-not $approved.Count) {
        [Windows.Forms.MessageBox]::Show($(if($en){"There are no approved restores.`n`nOpen your account, choose a backup and wait for approval."}else{"Non ci sono ripristini approvati.`n`nApri l'area personale, scegli un backup e attendi l'approvazione."}), 'RansomBackup FREE', 'OK', 'Information') | Out-Null
        exit 0
    }

    $form = New-Object Windows.Forms.Form
    $form.Text = if($en){'Restore files — RansomBackup FREE'}else{'Ripristina file — RansomBackup FREE'}
    $form.ClientSize = New-Object Drawing.Size(680, 340)
    $form.StartPosition = 'CenterScreen'; $form.FormBorderStyle = 'FixedDialog'; $form.MaximizeBox = $false
    $form.BackColor = [Drawing.Color]::FromArgb(247,249,248); $form.Font = New-Object Drawing.Font('Segoe UI',10); $form.AutoScaleMode='Dpi'
    $title = New-Object Windows.Forms.Label
    $title.Text = if($en){'Restore without overwriting anything'}else{'Ripristina senza sovrascrivere nulla'}; $title.Font = New-Object Drawing.Font('Segoe UI Semibold',19); $title.Location=New-Object Drawing.Point(26,22);$title.AutoSize=$true;$form.Controls.Add($title)
    $copy = New-Object Windows.Forms.Label
    $copy.Text = if($en){'Files will be copied to a new folder. Originals will not be changed.'}else{'I file verranno copiati in una nuova cartella. Gli originali non saranno modificati.'};$copy.Location=New-Object Drawing.Point(29,68);$copy.AutoSize=$true;$form.Controls.Add($copy)
    $label = New-Object Windows.Forms.Label;$label.Text=if($en){'Approved backup'}else{'Backup approvato'};$label.Location=New-Object Drawing.Point(29,112);$label.AutoSize=$true;$form.Controls.Add($label)
    $selector = New-Object Windows.Forms.ComboBox;$selector.DropDownStyle='DropDownList';$selector.Location=New-Object Drawing.Point(32,138);$selector.Size=New-Object Drawing.Size(615,32);$form.Controls.Add($selector)
    foreach($item in $approved){[void]$selector.Items.Add("$([DateTimeOffset]::FromUnixTimeSeconds([int64]$item.requested_at).LocalDateTime.ToString('g')) · snapshot $($item.snapshot_id.Substring(0,8))")}
    $selector.SelectedIndex=0
    $destinationLabel=New-Object Windows.Forms.Label;$destinationLabel.Text=if($en){'Folder in which to create the restore'}else{'Cartella nella quale creare il ripristino'};$destinationLabel.Location=New-Object Drawing.Point(29,190);$destinationLabel.AutoSize=$true;$form.Controls.Add($destinationLabel)
    $destination=New-Object Windows.Forms.TextBox;$destination.Location=New-Object Drawing.Point(32,216);$destination.Size=New-Object Drawing.Size(480,30);$destination.ReadOnly=$true;$form.Controls.Add($destination)
    $browse=New-Object Windows.Forms.Button;$browse.Text=if($en){'Choose…'}else{'Scegli…'};$browse.Location=New-Object Drawing.Point(526,213);$browse.Size=New-Object Drawing.Size(121,38);Set-RBSecondaryButton $browse;$form.Controls.Add($browse)
    $start=New-Object Windows.Forms.Button;$start.Text=if($en){'Start restore'}else{'Avvia ripristino'};$start.Location=New-Object Drawing.Point(467,276);$start.Size=New-Object Drawing.Size(180,44);Set-RBPrimaryButton $start;$form.Controls.Add($start)
    $browse.Add_Click({$dialog=New-Object Windows.Forms.FolderBrowserDialog;$dialog.Description=if($en){'Choose where to create the new restore folder'}else{'Scegli dove creare la nuova cartella di ripristino'};if($dialog.ShowDialog()-eq 'OK'){$destination.Text=$dialog.SelectedPath}})
    $start.Add_Click({if(-not $destination.Text){[Windows.Forms.MessageBox]::Show($(if($en){'Choose a destination folder first.'}else{'Scegli prima una cartella di destinazione.'}),'RansomBackup FREE','OK','Warning')|Out-Null;return};$form.Tag='start';$form.Close()})
    [void]$form.ShowDialog()
    if($form.Tag-ne 'start'){exit 0}

    $selected=$approved[$selector.SelectedIndex]
    $claim=Invoke-RestMethod -Method Post -Uri "$($state.Config.gateway)/api/v1/restore-requests/$($selected.id)/claim" -Headers (Get-RBBasicHeader $state) -ContentType 'application/json' -Body '{}' -TimeoutSec 30
    $targetName=$(if($en){'RansomBackup-Restore-'}else{'RansomBackup-Ripristino-'})+(Get-Date -Format 'yyyyMMdd-HHmmss')+'-'+$claim.snapshot_id.Substring(0,8)
    $target=Join-Path $destination.Text $targetName
    if(Test-Path -LiteralPath $target){throw $(if($en){'The restore folder already exists.'}else{'La cartella di ripristino esiste già.'})}
    [void][IO.Directory]::CreateDirectory($target)
    $success=$false;$restoreOutput=@()
    try {
        Set-RBResticEnvironment -State $state -RestoreToken $claim.restore_token
        $restoreOutput=& $state.Paths.Restic --cache-dir $state.Paths.Cache restore $claim.snapshot_id --target $target --verify 2>&1
        $success=($LASTEXITCODE -eq 0)
    } finally {
        Clear-RBResticEnvironment
        $completeBody=@{success=$success;note=if($success){'Ripristino completato dal client Windows'}else{'Restic ha restituito un errore'}}|ConvertTo-Json
        try{Invoke-RestMethod -Method Post -Uri "$($state.Config.gateway)/api/v1/restore-requests/$($selected.id)/complete" -Headers (Get-RBBasicHeader $state) -ContentType 'application/json' -Body $completeBody -TimeoutSec 30|Out-Null}catch{}
    }
    New-Item -ItemType Directory -Force -Path $state.Paths.Logs|Out-Null
    Add-Content -LiteralPath (Join-Path $state.Paths.Logs 'restore.log') -Encoding UTF8 -Value @("`n===== $(Get-Date -Format s) snapshot=$($claim.snapshot_id.Substring(0,8)) success=$success =====",$restoreOutput)
    if(-not $success){throw $(if($en){'Restore failed. Details are in the log; original files were not changed.'}else{'Il ripristino non è riuscito. I dettagli sono nel log; i file originali non sono stati modificati.'})}
    [Windows.Forms.MessageBox]::Show($(if($en){"Restore complete.`n`nFiles are in the new folder:`n$target"}else{"Ripristino completato.`n`nI file sono nella nuova cartella:`n$target"}),'RansomBackup FREE','OK','Information')|Out-Null
    Start-Process explorer.exe -ArgumentList @("`"$target`"")
} catch {
    [Windows.Forms.MessageBox]::Show($(if($en){"Restore was not completed.`n`n$($_.Exception.Message)"}else{"Ripristino non completato.`n`n$($_.Exception.Message)"}),'RansomBackup FREE','OK','Error')|Out-Null
    exit 1
}
