. (Join-Path $PSScriptRoot "Common.ps1")

$lockFile = Get-RalphStateFile -Name "inbox_daemon.lock.json"
$daemonStateFile = Get-RalphStateFile -Name "inbox_daemon_state.json"

if (-not (Test-Path $lockFile)) {
    @{
        stopped = $false
        message = "No inbox daemon lock file found."
    } | ConvertTo-Json -Depth 20
    return
}

$lock = Read-JsonFile -Path $lockFile
$daemonPid = 0
try { $daemonPid = [int]$lock.pid } catch { $daemonPid = 0 }

if ($daemonPid -le 0) {
    Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue
    @{
        stopped = $false
        message = "Lock file was invalid and has been removed."
    } | ConvertTo-Json -Depth 20
    return
}

$proc = Get-Process -Id $daemonPid -ErrorAction SilentlyContinue
if ($null -ne $proc) {
    Stop-Process -Id $daemonPid -Force
}

Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue
Write-JsonFile -Path $daemonStateFile -Object ([ordered]@{
    pid = $daemonPid
    status = "stopped"
    message = "Inbox daemon stopped manually."
    updated_at = (Get-Date).ToString("o")
})

Add-RalphEvent -RunId ("inbox-daemon-stop-" + (Get-Date -Format "yyyyMMdd-HHmmss")) -Stage "daemon" -Status "stopped" -Actor "stop" -Message "Inbox daemon stopped manually" -Data @{
    pid = $daemonPid
}
Send-TelegramNotification `
    -EventName "daemon_stopped" `
    -Title "Ralph daemon stopped manually" `
    -Message ("PID " + $daemonPid) `
    -RunId ("inbox-daemon-stop-" + (Get-Date -Format "yyyyMMdd-HHmmss")) `
    -Stage "daemon" `
    -Status "stopped" | Out-Null

@{
    stopped = $true
    pid = $daemonPid
} | ConvertTo-Json -Depth 20
