Functions/Ses/Sesio-Run.ps1

# Import utilities
. $PSScriptRoot\..\Util.ps1

function Sesio-Run {
    param (
        [Parameter(Position=0, Mandatory=$true)]
        [string]$Command,
        
        [Parameter(ValueFromRemainingArguments=$true)]
        $RemainingArgs
    )
    switch ($Command.ToLower()) {
        "help" { Sesio-Run-Help }
        "status" { 
              
            $params = @{}
            for ($i = 0; $i -lt $RemainingArgs.Count; $i += 2) {
                if ($i + 1 -lt $RemainingArgs.Count) {
                    $params[$RemainingArgs[$i].TrimStart('-')] = $RemainingArgs[$i + 1]
                }
            }
            Sesio-Run-Status @params 
        }
        default { Sesio-Arc-Run @RemainingArgs }
    }   
}

function Sesio-Arc-Run {
    param(
        [Parameter(Mandatory=$false)]
        [string]$path,
        
        [Parameter(Mandatory=$false)]
        [int]$pollInterval = 2
    )

    if($path -eq $null) {
        $path = Join-Path (Get-Location) 
    }
    else {
        $path = Join-Path (Get-Location) $path 
    }

    $aarcFilePath = Join-Path $path ".sesio/default.aarc"
     if(-not (Test-Path $aarcFilePath)) {
        Write-Error "Arc file not found at: $aarcFilePath"
        return
     }

      # Read URL from .env file in .sesio folder
    $sesioFolder = Join-Path $env:USERPROFILE ".sesio"
    $envFile = Join-Path $sesioFolder ".env"

    $url = $null
    if (Test-Path $envFile) {
        Get-Content $envFile | ForEach-Object {
            if ($_ -match "^url=(.*)$") {
                $url = $matches[1]
            }
        }
    }
    Write-Host "URL: $url"

    $UploadUrl = "$url/api/start-orchestration"

    # Read and upload the AARC file
    try {
        $aarcContent = Get-Content $aarcFilePath -Raw
        # Write-Host "AARC Content: $aarcContent"
        
        # Modified form data construction
        $boundary = [System.Guid]::NewGuid().ToString()
        $LF = "`r`n"
        $bodyLines = (
            "--$boundary",
            "Content-Disposition: form-data; name=`"aarcFile`"",
            "Content-Type: text/aarc",
            "",
            $aarcContent,
            "--$boundary--"
        ) -join $LF

        # Set headers with multipart boundary
        $headers = @{
            "Content-Type" = "multipart/form-data; boundary=$boundary"
        }

        $response = Invoke-RestMethod -Uri $UploadUrl -Method Post -Body $bodyLines -Headers $headers
        Write-Host "Successfully uploaded AARC file"
        Write-Host "Instance ID: $($response.id)"
        Write-Host "Status URL: $($response.statusQueryGetUri)"
        Start-Process $response.statusQueryGetUri
        
        while ($true) {
            $status = Invoke-RestMethod -Uri $response.statusQueryGetUri -Method Get
            Write-Host "`rStatus: $($status.runtimeStatus) " -NoNewline
            
            if ($status.runtimeStatus -in @('Completed', 'Failed', 'Terminated', 'Suspended')) {
                #Write-Host "`nFinal Status: $($status.runtimeStatus)"
                return 'Finished up'
            }
            
            Start-Sleep -Seconds 2
        }
    }
    catch {
        Write-Error "Failed: $_"
        return
    }
}

function Sesio-Internal-Status {
    param(
        [Parameter(Mandatory=$true)]
        [string]$instanceId,
        
        [Parameter(Mandatory=$false)]
        [int]$pollInterval = 2
    )

    $sesioFolder = Join-Path $env:USERPROFILE ".sesio"
    $envFile = Join-Path $sesioFolder ".env"

    $url = $null
    if (Test-Path $envFile) {
        Get-Content $envFile | ForEach-Object {
            if ($_ -match "^url=(.*)$") {
                $url = $matches[1]
            }
        }
    }

    $statusUrl = "$url/api/check-orchestration-status/$instanceId"
    
    try {
        while ($true) {
            $response = Invoke-RestMethod -Uri $statusUrl -Method Get
            
            # Return the response object for terminal states
            switch ($response.runtimeStatus) {
                "Completed" { return @{ status = $response.runtimeStatus; data = $response } }
                "Failed" { return @{ status = $response.runtimeStatus; data = $response; error = $response.failureDetails } }
                "Terminated" { return @{ status = $response.runtimeStatus; data = $response } }
                "Suspended" { return @{ status = $response.runtimeStatus; data = $response } }
            }
            
            Start-Sleep -Seconds $pollInterval
        }
    }
    catch {
        return @{ 
            status = "Error"
            error = $_.Exception.Message
            data = $null
        }
    }
}

function Sesio-Run-Status {
    param(
        [Parameter(Mandatory=$true)]
        [string]$instanceId,
        
        [Parameter(Mandatory=$false)]
        [int]$pollInterval = 2  # Polling interval in seconds
    )
    
    $sesioFolder = Join-Path $env:USERPROFILE ".sesio"
    $envFile = Join-Path $sesioFolder ".env"

    $url = $null
    if (Test-Path $envFile) {
        Get-Content $envFile | ForEach-Object {
            if ($_ -match "^url=(.*)$") {
                $url = $matches[1]
            }
        }
    }

    $statusUrl = "$url/api/check-orchestration-status/$instanceId"
    
    Write-Host "Monitoring orchestration status... (Press Ctrl+C to stop)"
    Write-Host "----------------------------------------"
    
    try {
        while ($true) {
            $response = Invoke-RestMethod -Uri $statusUrl -Method Get
            
            # Clear the previous line
            Write-Host "`rStatus: $($response.runtimeStatus) " -NoNewline
            
            if ($response.runtimeStatus -in @('Completed', 'Failed', 'Terminated')) {
                Write-Host "`nOrchestration finished with status: $($response.runtimeStatus)"
                return $response
            }
            
            Start-Sleep -Seconds $pollInterval
        }
    }
    catch {
        Write-Error "Failed to get status: $_"
        return
    }
}

function Sesio-Run-Help {
    Write-Host "$infoColor Sesio Run Help $resetColor"
    Write-Host ""
    Write-Host "$infoColor Usage: sesio run [command] [options]$resetColor"
    Write-Host ""
    Write-Host "$infoColor Commands:$resetColor"
    Write-Host "$([char]0x1b)[32m--------------------------------$([char]0x1b)[0m"
    Write-Host "$([char]0x1b)[31mstatus$([char]0x1b)[0m - Check orchestration status"
    Write-Host " Options:"
    Write-Host " -instanceId The ID of the running orchestration"
    Write-Host ""
    Write-Host "$([char]0x1b)[31m<path>$([char]0x1b)[0m - Run orchestration ($([char]0x1b)[33moptional$([char]0x1b)[0m)"
    Write-Host " Optional path to the orchestration directory"
    Write-Host " If not provided, uses current directory"
    Write-Host "$([char]0x1b)[32m--------------------------------$([char]0x1b)[0m"
    Write-Host ""
    Write-Host "Examples:"
    Write-Host " sesio run status -instanceId abc123"
    Write-Host " sesio run"
    Write-Host " sesio run ./my-project"
}

export-modulemember -function Sesio-Run