#!/usr/bin/env pwsh

<#
.SYNOPSIS
Start Job 893 Phase 1 Shadow Run monitoring in background

.DESCRIPTION
Monitors Job 893 progress every 5 minutes
- Displays current status, progress, rows processed
- Detects completion (Completed/Failed)
- Logs to file for historical tracking

.EXAMPLE
./START_JOB_893_MONITOR.ps1
#>

$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
$repoRoot = Split-Path -Parent $scriptPath
$logFile = Join-Path $scriptPath "Job893_Monitor_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"

Write-Host "=== Job 893 Monitoring ===" -ForegroundColor Cyan
Write-Host "Repo: $repoRoot" -ForegroundColor White
Write-Host "Log file: $logFile" -ForegroundColor White

# Compile monitoring script
Write-Host "`n=== Compiling Monitor ===" -ForegroundColor Cyan

$csharpFile = Join-Path $scriptPath "MonitorJob893.cs"
$exePath = Join-Path $scriptPath "MonitorJob893.exe"

if (-not (Test-Path $csharpFile)) {
    Write-Error "MonitorJob893.cs not found at $csharpFile"
    exit 1
}

# Compile with csc.exe (included in .NET SDK)
$dotnetSdk = & dotnet --version 2>$null
if (-not $dotnetSdk) {
    Write-Error "dotnet SDK not found"
    exit 1
}

Write-Host "✅ .NET SDK version: $dotnetSdk" -ForegroundColor Green

# Compile using dotnet cli
Write-Host "`n=== Compiling with dotnet ===" -ForegroundColor Cyan

$tempProject = Join-Path $scriptPath "MonitorJob893.csproj"

@"
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>latest</LangVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Npgsql" Version="9.0.0" />
  </ItemGroup>
</Project>
"@ | Set-Content -Path $tempProject

try {
    Push-Location $scriptPath

    # Restore and compile
    & dotnet build -o "." -c Release MonitorJob893.csproj 2>&1 | Out-Null

    if ($LASTEXITCODE -ne 0) {
        Write-Host "⚠️ Compilation with project file failed, trying direct CSC..." -ForegroundColor Yellow

        # Try simpler approach: use dotnet run
        Write-Host "Using dotnet run approach..." -ForegroundColor Yellow
        $exePath = "dotnet"
    }
    else {
        Write-Host "✅ Compiled successfully" -ForegroundColor Green
    }
} finally {
    Pop-Location
}

# Start monitoring in background
Write-Host "`n=== Starting Monitor ===" -ForegroundColor Cyan

$monitorCommand = if ($exePath -eq "dotnet") {
    "dotnet run --project '$tempProject' --"
} else {
    "'$exePath'"
}

$job = Start-Job -ScriptBlock {
    param($cmd, $log)

    # Start monitoring
    Invoke-Expression "$cmd" | Tee-Object -FilePath $log -Append
} -ArgumentList $monitorCommand, $logFile

Write-Host "✅ Monitor started (Job ID: $($job.Id))" -ForegroundColor Green
Write-Host "PID: $($job.PSChildJobs[0].Id)" -ForegroundColor White
Write-Host "Log file: $logFile" -ForegroundColor White

Write-Host "`n=== Commands ===" -ForegroundColor Cyan
Write-Host "View logs:" -ForegroundColor White
Write-Host "  Get-Content '$logFile' -Tail 20 -Wait" -ForegroundColor Cyan
Write-Host "`nStop monitor:" -ForegroundColor White
Write-Host "  Stop-Job -Id $($job.Id)" -ForegroundColor Cyan
Write-Host "`nCheck status:" -ForegroundColor White
Write-Host "  Get-Job -Id $($job.Id) | Select-Object State, HasMoreData" -ForegroundColor Cyan

# Display initial check
Write-Host "`n=== Initial Status ===" -ForegroundColor Cyan
Start-Sleep -Seconds 2
if ($job.State -eq "Running") {
    Write-Host "✅ Monitor is running" -ForegroundColor Green
    Write-Host "`n[Monitor output will appear in log file above]" -ForegroundColor Gray
    Write-Host "Next auto-update in 5 minutes..." -ForegroundColor Gray
} else {
    Write-Host "⚠️ Monitor job state: $($job.State)" -ForegroundColor Yellow
}
