$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'Common.ps1')
$state = $null
$exitCode = 1
try {
    $state = Get-RBConfiguration
    $configuredSources = @(Get-RBSources $state)
    $validSources = @($configuredSources | Where-Object { Test-Path -LiteralPath $_ -PathType Container })
    $missingSources = @($configuredSources | Where-Object { -not (Test-Path -LiteralPath $_ -PathType Container) })
    if (-not $validSources.Count) {
        Send-RBClientReport -State $state -Status 'source_missing' -ExitCode 2
        throw "Nessuna cartella configurata è disponibile: $($configuredSources -join ', ')"
    }
    if (-not (Test-Path -LiteralPath $state.Paths.Restic)) { throw 'restic.exe non trovato.' }
    New-Item -ItemType Directory -Force -Path $state.Paths.Cache, $state.Paths.Logs | Out-Null
    $account = Get-RBAccountState -State $state
    Show-RBQuotaNotice -State $state -Account $account
    if (-not $account.backup_allowed) {
        $exitCode = 23
        [pscustomobject]@{ timestamp=[DateTimeOffset]::UtcNow.ToUnixTimeSeconds(); status='quota_reached'; exit_code=$exitCode } | ConvertTo-Json | Set-Content -LiteralPath $state.Paths.Status -Encoding UTF8
        [void](Send-RBClientReport -State $state -Status 'quota_reached' -ExitCode $exitCode)
        Add-Content -LiteralPath (Join-Path $state.Paths.Logs 'backup.log') -Encoding UTF8 -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') Quota FREE raggiunta: backup non avviato."
        exit $exitCode
    }
    $hasCache = Get-ChildItem -LiteralPath $state.Paths.Cache -Recurse -File -ErrorAction SilentlyContinue | Select-Object -First 1
    $arguments = @('--cache-dir', $state.Paths.Cache, 'backup')
    if (-not $hasCache) { $arguments += '--force' }
    $arguments += @('--tag', 'ransombackup-free')
    $arguments += $validSources
    Set-RBResticEnvironment -State $state
    $output = & $state.Paths.Restic @arguments 2>&1
    $exitCode = $LASTEXITCODE
    $stamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    Add-Content -LiteralPath (Join-Path $state.Paths.Logs 'backup.log') -Encoding UTF8 -Value @("`n===== $stamp exit=$exitCode =====", $output)
    if ($missingSources.Count) { Add-Content -LiteralPath (Join-Path $state.Paths.Logs 'backup.log') -Encoding UTF8 -Value "Cartelle non disponibili: $($missingSources -join ', ')" }
    $status = if ($exitCode -eq 0 -and -not $missingSources.Count) { 'backup_ok' } elseif ($exitCode -eq 0) { 'source_missing' } else { 'backup_failed' }
    [pscustomobject]@{ timestamp=[DateTimeOffset]::UtcNow.ToUnixTimeSeconds(); status=$status; exit_code=$exitCode } | ConvertTo-Json | Set-Content -LiteralPath $state.Paths.Status -Encoding UTF8
    $report = Send-RBClientReport -State $state -Status $status -ExitCode $exitCode
    if ($report -and $report.account) { Show-RBQuotaNotice -State $state -Account $report.account }
    if ($exitCode -eq 0) {
        $snapshotOutput = & $state.Paths.Restic --cache-dir $state.Paths.Cache snapshots --json 2>$null
        if ($LASTEXITCODE -eq 0) {
            $snapshots = @(($snapshotOutput -join [Environment]::NewLine) | ConvertFrom-Json)
            Send-RBSnapshotCatalog -State $state -Snapshots $snapshots
        }
    }
} catch {
    if ($state) { Send-RBClientReport -State $state -Status 'backup_failed' -ExitCode $exitCode }
    $paths = Get-RBPaths
    New-Item -ItemType Directory -Force -Path $paths.Logs | Out-Null
    Add-Content -LiteralPath (Join-Path $paths.Logs 'backup.log') -Encoding UTF8 -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ERROR: $($_.Exception.Message)"
} finally {
    Clear-RBResticEnvironment
}
exit $exitCode
