# =============================================================================
#  CUBIE TEP - LLM VERBOSE / THINKING CAPTURE
#  Sends a representative window from d00 (NORMAL), d03 (IDV-3 active),
#  d15 (IDV-15 active) to Haiku 4.5 + Sonnet 4.6 + Opus 4.7.
#  Sonnet + Opus get extended thinking enabled; Haiku gets explanation mode.
#  Prints each model's full reasoning + answer.
# =============================================================================

$ErrorActionPreference = "Continue"
$RepoDir   = "C:\Users\NickV\cubie-tf-completion"
$WindowLen = 20
$dataDir   = "$RepoDir\data\tep"

# --- key load (env first, then .env.portal fallback) ----------------------
$anthropicCredential = $env:ANTHROPIC_API_KEY
if (-not $anthropicCredential) {
    $envFile = "C:\Users\NickV\OneDrive\Desktop\RAKKIT STACK\.env.portal"
    if (Test-Path $envFile) {
        $line = Get-Content $envFile | Where-Object { $_ -match "^ANTHROPIC_API_KEY=" } | Select-Object -First 1
        if ($line) { $anthropicCredential = ($line -split '=', 2)[1].Trim() }
    }
}
if (-not $anthropicCredential) { Write-Host "No API key found"; exit 1 }
$mask = $anthropicCredential.Substring(0, 15) + "..." + $anthropicCredential.Substring($anthropicCredential.Length - 6)
Write-Host "Key in use: $mask"
Write-Host ""

# --- load 3 windows ---------------------------------------------------------
function Load-Window($file, $startIdx, $len) {
    # CSV format: faultNumber, simulationRun, sample, xmeas_1..xmeas_52
    # Skip header row (text); skip first 3 metadata columns; keep xmeas_1..xmeas_22
    $rows = @()
    $first = $true
    foreach ($line in (Get-Content $file)) {
        if ($first) { $first = $false; continue }  # skip header
        $parts = $line.Trim() -split ','
        if ($parts.Count -lt 25) { continue }  # need 3 meta + 22 sensors
        try {
            $vals = @()
            for ($i = 3; $i -lt 25; $i++) { $vals += [double]$parts[$i] }
            $rows += ,$vals
        } catch { continue }
    }
    return $rows[$startIdx..($startIdx + $len - 1)]
}

$winNormal = Load-Window "$dataDir\d00_test.csv" 0   $WindowLen   # d00, NORMAL throughout
$winFault3 = Load-Window "$dataDir\d03_test.csv" 200 $WindowLen   # d03, well past sample 161
$winFault15 = Load-Window "$dataDir\d15_test.csv" 200 $WindowLen  # d15, well past sample 161

$varLabels = @(
    "XMEAS(1) A feed (stream 1)",   "XMEAS(2) D feed (stream 2)",
    "XMEAS(3) E feed (stream 3)",   "XMEAS(4) A+C feed (stream 4)",
    "XMEAS(5) recycle flow",        "XMEAS(6) reactor feed rate",
    "XMEAS(7) reactor pressure",    "XMEAS(8) reactor level",
    "XMEAS(9) reactor temp",        "XMEAS(10) purge rate (stream 9)",
    "XMEAS(11) sep temp",           "XMEAS(12) sep level",
    "XMEAS(13) sep pressure",       "XMEAS(14) sep underflow",
    "XMEAS(15) stripper level",     "XMEAS(16) stripper pressure",
    "XMEAS(17) stripper underflow", "XMEAS(18) stripper temp",
    "XMEAS(19) stripper steam flow","XMEAS(20) compressor work",
    "XMEAS(21) reactor CW out temp","XMEAS(22) condenser CW out temp"
)

function Format-Window($win) {
    $sb = New-Object System.Text.StringBuilder
    for ($v = 0; $v -lt 22; $v++) {
        $vals = @()
        for ($t = 0; $t -lt $win.Count; $t++) { $vals += "{0,8:F3}" -f $win[$t][$v] }
        [void]$sb.AppendLine(("  {0,-32}  {1}" -f $varLabels[$v], ($vals -join "")))
    }
    $sb.ToString()
}

# --- prompts --------------------------------------------------------------
$systemPromptThinking = @"
You are a chemical process control engineer monitoring the Tennessee Eastman
Process (TEP), a benchmark simulation of a fluid catalytic cracking unit
published by Downs and Vogel (1993, Eastman Chemical Co.). The TEP has 52
sensor variables and 20 documented fault modes (IDV-1 through IDV-20). The
process runs with closed-loop control that compensates quickly when faults
occur, so fault signatures can be subtle.

You will be shown a sliding window of the 22 primary measurement variables
(XMEAS(1) through XMEAS(22)), sampled every 3 minutes. Decide whether a
process fault is currently active in this window.

Think through what you see — variability, trends, drift, value ranges — and
then give your verdict. End your response with the literal string
FINAL_ANSWER: FAULT  or  FINAL_ANSWER: NORMAL
"@

$systemPromptHaikuExplain = @"
You are a chemical process control engineer monitoring the Tennessee Eastman
Process (TEP), a benchmark simulation of a fluid catalytic cracking unit
published by Downs and Vogel (1993, Eastman Chemical Co.). The TEP has 52
sensor variables and 20 documented fault modes (IDV-1 through IDV-20). The
process runs with closed-loop control that compensates quickly when faults
occur, so fault signatures can be subtle.

You will be shown a sliding window of the 22 primary measurement variables
(XMEAS(1) through XMEAS(22)), sampled every 3 minutes. Decide whether a
process fault is currently active in this window.

Give 3-4 sentences of reasoning, then end with the literal string
FINAL_ANSWER: FAULT  or  FINAL_ANSWER: NORMAL
"@

function Build-UserPrompt($win) {
    "Window of 20 samples (3-min interval), 22 primary measurement variables:`n`n" + (Format-Window $win) + "`nAssess whether a process fault is active in this window."
}

# --- API call (with optional thinking) ----------------------------------------
function Call-Anthropic($model, $userPrompt, $useThinking) {
    $headers = @{
        'x-api-key' = $anthropicCredential
        'anthropic-version' = '2023-06-01'
        'content-type' = 'application/json'
    }
    if ($useThinking) {
        # Opus 4.7 uses adaptive thinking, older Sonnets use type=enabled with budget_tokens
        if ($model -match 'opus-4-7') {
            $bodyHash = @{
                model       = $model
                max_tokens  = 4000
                system      = $systemPromptThinking
                messages    = @(@{ role = 'user'; content = $userPrompt })
                thinking    = @{ type = 'adaptive' }
                output_config = @{ effort = 'medium' }
            }
        } else {
            $bodyHash = @{
                model       = $model
                max_tokens  = 4000
                system      = $systemPromptThinking
                messages    = @(@{ role = 'user'; content = $userPrompt })
                thinking    = @{ type = 'enabled'; budget_tokens = 2000 }
            }
        }
    } else {
        $bodyHash = @{
            model       = $model
            max_tokens  = 1500
            system      = $systemPromptHaikuExplain
            messages    = @(@{ role = 'user'; content = $userPrompt })
        }
    }
    $body = $bodyHash | ConvertTo-Json -Depth 6
    try {
        $r = Invoke-RestMethod -Method Post -Uri 'https://api.anthropic.com/v1/messages' -Headers $headers -Body $body
        $thinking = ($r.content | Where-Object { $_.type -eq 'thinking' } | ForEach-Object { $_.thinking }) -join "`n"
        $text     = ($r.content | Where-Object { $_.type -eq 'text' }     | ForEach-Object { $_.text })     -join "`n"
        $verdict = if ($text -match 'FINAL_ANSWER:\s*FAULT')   { 'FAULT' }
                   elseif ($text -match 'FINAL_ANSWER:\s*NORMAL') { 'NORMAL' }
                   else { '?' }
        return @{
            ok = $true
            thinking = $thinking
            text = $text
            verdict = $verdict
            usage = $r.usage
        }
    } catch {
        return @{ ok = $false; thinking = ''; text = $_.ErrorDetails.Message; verdict = 'ERROR'; usage = @{} }
    }
}

# --- test cases ------------------------------------------------------------
$cases = @(
    @{ Label = "d00 sample 0..19  (FAULT-FREE baseline)";       Win = $winNormal; Expected = "NORMAL" },
    @{ Label = "d03 sample 200..219 (IDV-3 D-feed temp step)";  Win = $winFault3;  Expected = "FAULT"  },
    @{ Label = "d15 sample 200..219 (IDV-15 condenser CW valve)";Win = $winFault15; Expected = "FAULT" }
)

$models = @(
    @{ Id = "claude-haiku-4-5-20251001"; Thinking = $false },
    @{ Id = "claude-sonnet-4-6";         Thinking = $true  },
    @{ Id = "claude-opus-4-7";           Thinking = $true  }
)

$allOut = @()

foreach ($m in $models) {
    Write-Host ""
    Write-Host ("#" * 78) -ForegroundColor Cyan
    Write-Host ("# MODEL: $($m.Id)" + $(if ($m.Thinking) { '   (extended thinking ENABLED)' } else { '   (explain-mode, no thinking blocks)' })) -ForegroundColor Cyan
    Write-Host ("#" * 78) -ForegroundColor Cyan

    foreach ($c in $cases) {
        Write-Host ""
        Write-Host ("-" * 78) -ForegroundColor Yellow
        Write-Host ("WINDOW: $($c.Label)") -ForegroundColor Yellow
        Write-Host ("EXPECTED: $($c.Expected)") -ForegroundColor Yellow
        Write-Host ("-" * 78) -ForegroundColor Yellow

        $userPrompt = Build-UserPrompt $c.Win
        $r = Call-Anthropic $m.Id $userPrompt $m.Thinking

        if ($r.thinking) {
            Write-Host ""
            Write-Host "<thinking>" -ForegroundColor Magenta
            Write-Host $r.thinking -ForegroundColor DarkGray
            Write-Host "</thinking>" -ForegroundColor Magenta
        }
        Write-Host ""
        Write-Host "<response>" -ForegroundColor Green
        Write-Host $r.text -ForegroundColor White
        Write-Host "</response>" -ForegroundColor Green
        Write-Host ""
        $hit = ($r.verdict -eq $c.Expected)
        $color = if ($hit) { "Green" } else { "Red" }
        Write-Host ("VERDICT: $($r.verdict)     EXPECTED: $($c.Expected)     $(if ($hit) {'CORRECT'} else {'WRONG'})") -ForegroundColor $color
        if ($r.usage) {
            Write-Host ("Tokens: input=$($r.usage.input_tokens) output=$($r.usage.output_tokens)") -ForegroundColor DarkGray
        }

        $allOut += @{
            model = $m.Id
            window = $c.Label
            expected = $c.Expected
            thinking = $r.thinking
            response = $r.text
            verdict = $r.verdict
            correct = $hit
            usage = $r.usage
        }
    }
}

# --- save JSON -------------------------------------------------------------
$outFile = "$RepoDir\data\tep\layouts\llm_verbose_$(Get-Date -f 'yyyyMMdd_HHmmss').json"
$allOut | ConvertTo-Json -Depth 10 | Set-Content -Path $outFile -Encoding UTF8
Write-Host ""
Write-Host ("=" * 78) -ForegroundColor Cyan
Write-Host ("Full transcript saved: $outFile") -ForegroundColor Cyan
Write-Host ("=" * 78) -ForegroundColor Cyan
