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

$roots = Get-RalphTaskRoots
$lockFile = Get-RalphStateFile -Name "inbox_daemon.lock.json"
$daemonStateFile = Get-RalphStateFile -Name "inbox_daemon_state.json"
$currentRunFile = Get-RalphStateFile -Name "current_run.json"
$backgroundFile = Join-Path (Get-RalphRoot) "state\last_inbox_background.json"

function Get-ItemCount {
    param([object[]]$Items)
    return [int](($Items | Measure-Object).Count)
}

$result = [ordered]@{
    inbox = [ordered]@{
        queued_taskpacks = Get-ItemCount -Items @(Get-ChildItem -LiteralPath $roots.Inbox -Directory -ErrorAction SilentlyContinue | Where-Object { Test-Path (Join-Path $_.FullName "TASK.md") })
        queued_markdown_files = Get-ItemCount -Items @(Get-ChildItem -LiteralPath $roots.Inbox -File -Filter *.md -ErrorAction SilentlyContinue)
        processing = Get-ItemCount -Items @(Get-ChildItem -LiteralPath $roots.Processing -Directory -ErrorAction SilentlyContinue)
        completed = Get-ItemCount -Items @(Get-ChildItem -LiteralPath $roots.Completed -Directory -ErrorAction SilentlyContinue)
        failed = Get-ItemCount -Items @(Get-ChildItem -LiteralPath $roots.Failed -Directory -ErrorAction SilentlyContinue)
    }
    daemon = $null
    current_run = $null
    background = $null
}

if (Test-Path $lockFile) {
    try {
        $result.daemon = Read-JsonFile -Path $lockFile
    }
    catch {
        $result.daemon = @{ error = $_.Exception.Message }
    }
}

if (Test-Path $daemonStateFile) {
    try {
        $result.daemon_state = Read-JsonFile -Path $daemonStateFile
    }
    catch {
        $result.daemon_state = @{ error = $_.Exception.Message }
    }
}

if (Test-Path $currentRunFile) {
    try {
        $result.current_run = Read-JsonFile -Path $currentRunFile
    }
    catch {
        $result.current_run = @{ error = $_.Exception.Message }
    }
}

if (Test-Path $backgroundFile) {
    try {
        $result.background = Read-JsonFile -Path $backgroundFile
    }
    catch {
        $result.background = @{ error = $_.Exception.Message }
    }
}

($result | ConvertTo-Json -Depth 100)
