param(
    [string]$JobName,
    [string]$Env
)

# --- Parameter Validation ---
if (-not $JobName) {
    Write-Host "JobName parameter is required" -ForegroundColor Red
    exit 1
}
if (-not $Env) {
    Write-Host "Environment (Env) parameter is required" -ForegroundColor Red
    exit 1
}

# --- Execute Job ---
Write-Host "Submitting job: $JobName in environment: $Env" -ForegroundColor Cyan
$output = & "$env:rcbin\submit.exe" -DSN="DOESTAX.$Env.JOBS.BATCH.LIB($JobName)"
$exitCode = [int]$LASTEXITCODE
$isSuccess = 0

# --- Parse SYSLOG Path ---
$syslogPath = $null
$syslogFolder = "Not found"
$content = @()
$summary = @()

try {
    $syslogPath = $output | Select-String -Pattern "SYSLOG=\[(.*)\]" | ForEach-Object { $_.Matches.Groups[1].Value }
    
    if ($syslogPath -and (Test-Path $syslogPath)) {
        $syslogFolder = Split-Path $syslogPath -Parent
        $content = Get-Content $syslogPath -ErrorAction Stop
        $summary = $content | Select-String -Pattern "%Job Overall Stats:" -Context 0,7 | ForEach-Object {
            $_.Context.PostContext | Select-Object -Skip 1 -First 5
        }
    } else {
        Write-Host "SYSLOG path not found or inaccessible: $syslogPath" -ForegroundColor Yellow
        $summary = @("SYSLOG file not found in output", "Raw output:", $output -join "`n")
    }
}
catch {
    Write-Host "Error processing SYSLOG: $($_.Exception.Message)" -ForegroundColor Yellow
    $summary = @("Error reading SYSLOG: $($_.Exception.Message)", "Raw output:", $output -join "`n")
}

# --- Evaluate Return Codes ---
$successConditions = @(
    { $JobName -eq "GSIRQ300" -and $exitCode -eq 50 },
    { $JobName -eq "DTSGWAGE" -and $exitCode -eq 8 },
    { $JobName -eq "DTSGCHKS" -and $exitCode -eq 8 },
    { $JobName -eq "DTSGPAYT" -and $exitCode -eq 8 },
    { $JobName -eq "DTSBXACH" -and $exitCode -eq 2 },
    { $JobName -eq "DTSBXREL" -and $exitCode -eq 2 },
    { $JobName -eq "DTSMIN02" -and $exitCode -eq 4 },
    { $JobName -eq "DTSBE405" -and $exitCode -eq 910 },
    { $JobName -eq "DTSBXREJ" -and $exitCode -eq 4 },
    { $JobName -eq "DTSRQ444" -and $exitCode -eq 4 },
    { $exitCode -eq 0 }
)

if ($successConditions | Where-Object { & $_ }) {
    Write-Host "Job $JobName succeeded with code $exitCode" -ForegroundColor Green
    $isSuccess = 0
} else {
    Write-Host "Job $JobName failed with code $exitCode" -ForegroundColor Red
    $isSuccess = 1
    # Only use error if we don't have a proper summary
    if ($summary.Count -eq 0) {
        $summary = @($Error[0])
    }
}

# --- Email Notification ---
$smtpServer = "smtp4.dc.gov"
$fromEmail = "Dutas@dc.gov"
$toEmail = "neerajk@innovaconsulting.com"
$ccEmail = @("neerajk@innovaconsulting.com")

$emailBody = @"
<pre style='font-family: Courier, monospace;'>
DUTAS Batch Job: $JobName Execution Report
==========================================
$($summary -join "`n")
==========================================

Return Code: $exitCode
Status: $(if ($isSuccess -eq 0) { "SUCCESS" } else { "FAILED" })
JOBLOG Path: $syslogFolder
</pre>
"@

try {
    Send-MailMessage -SmtpServer $smtpServer -Port 25 `
        -From $fromEmail -To $toEmail -Cc $ccEmail `
        -Subject "DUTAS-[$Env] Job Status: $JobName - $(if ($isSuccess -eq 0) { 'SUCCESS' } else { 'FAILED' })" `
        -Body $emailBody -BodyAsHtml
    Write-Host "Email sent successfully to $toEmail" -ForegroundColor Cyan
}
catch {
    Write-Host "Failed to send email: $($_.Exception.Message)" -ForegroundColor Yellow
}

Write-Host "`n---------------------------------------------"
Write-Host "Job: $JobName | ExitCode: $exitCode | Status: $(if ($isSuccess -eq 0) { 'SUCCESS' } else { 'FAILED' })"
Write-Host "---------------------------------------------`n"

exit $isSuccess