param(
    [string]$SourceFile = "",
    [string]$Text = "",
    [string]$Title = "",
    [switch]$PassThru
)

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

if ([string]::IsNullOrWhiteSpace($SourceFile) -and [string]::IsNullOrWhiteSpace($Text)) {
    throw "Provide either -SourceFile or -Text."
}

$roots = Get-RalphTaskRoots
foreach ($path in $roots.Values) {
    Ensure-Directory -Path $path
}

if (-not [string]::IsNullOrWhiteSpace($SourceFile)) {
    $taskInfo = New-RalphTaskPackFromMarkdown -MarkdownPath $SourceFile -Title $Title
}
else {
    $tempName = "{0}.md" -f ([guid]::NewGuid().ToString("N"))
    $tempPath = Join-Path ([System.IO.Path]::GetTempPath()) $tempName
    try {
        Write-Utf8File -Path $tempPath -Content ($Text.Trim() + "`n")
        $taskInfo = New-RalphTaskPackFromMarkdown -MarkdownPath $tempPath -Title $Title
    }
    finally {
        if (Test-Path $tempPath) {
            Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue
        }
    }
}

Add-RalphEvent -RunId $taskInfo.id -Stage "submit" -Status "queued" -Actor "submit" -Message ("Task queued: " + $taskInfo.title) -Data @{
    task_directory = $taskInfo.task_directory
}
Send-TelegramNotification `
    -EventName "task_queued" `
    -Title "Task queued" `
    -Message ($taskInfo.title + "`n" + $taskInfo.task_directory) `
    -RunId $taskInfo.id `
    -Stage "submit" `
    -Status "queued" | Out-Null

$result = [ordered]@{
    id = $taskInfo.id
    title = $taskInfo.title
    state = "queued"
    task_directory = $taskInfo.task_directory
    task_file = $taskInfo.task_file
}

$json = ($result | ConvertTo-Json -Depth 20)
if ($PassThru) {
    $result
}
else {
    $json
}
