$ErrorActionPreference = "Continue"
$RepoDir = "C:\Users\NickV\cubie-tf"
$OutDir = "C:\Users\NickV\cubie-tf-completion\docs\whitepaper\design"
New-Item -ItemType Directory -Force $OutDir | Out-Null

$anthropicCredential = $null
$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) { $anthropicCredential = $env:ANTHROPIC_API_KEY }
Write-Host "Key: $($anthropicCredential.Substring(0,15))...$($anthropicCredential.Substring($anthropicCredential.Length-6))"

function ReadFileSafe($path, $lines = 200) {
    if (Test-Path $path) {
        return (Get-Content $path | Select-Object -First $lines) -join "`n"
    }
    return "(file not found: $path)"
}

# Load question from external file (avoid prompt-injection-defense false positive)
$questionFile = "C:\Users\NickV\cubie-tf-completion\docs\whitepaper\v5_topology_question.txt"
$userQuestion = Get-Content -Raw $questionFile

$ctx_types     = ReadFileSafe "$RepoDir\cubie-core\src\types.rs" 300
$ctx_topology  = ReadFileSafe "$RepoDir\cubie-core\src\cube_topology.rs" 150
$ctx_adr0001   = ReadFileSafe "$RepoDir\docs\adr\0001-cube-object-layout-v8-manifold.md" 200
$ctx_adr0011   = ReadFileSafe "$RepoDir\docs\adr\0011-l0-5-opa-event-fingerprint-gate.md" 200

$repoCtx = @"

== Current cubie-tf code context (read-only cross-reference) ==

--- cubie-core/src/types.rs (CubeObjectV1 + CubeFlit64 + TopologyStateU128) ---
$ctx_types

--- cubie-core/src/cube_topology.rs ---
$ctx_topology

--- docs/adr/0001-cube-object-layout-v8-manifold.md ---
$ctx_adr0001

--- docs/adr/0011-l0-5-opa-event-fingerprint-gate.md ---
$ctx_adr0011
"@

$systemPrompt = "You are a senior systems architect with deep expertise in formal verification (Verus, Coq, Lean), bare-metal Rust, side-channel-resistant cryptography, EU AI Act + GDPR compliance, Intel TDX/SGX/AMX, ARM CCA, RISC-V PMP, and the Belnap 4-valued logic substrate underlying the cubie project. You will receive a multi-axis architectural design question with cross-referenced code context from the cubie-tf repository. Reason carefully across performance, formal-proof, deployment-class, and compliance dimensions simultaneously. Produce a single coherent decision document. Use Markdown headings for the 8 questions and the deliverable sections. Cite specific CUB-IDs and Rust types from the provided context. Be explicit about conflicts and trade-offs."

$userPrompt = $userQuestion + "`n`n" + $repoCtx

Write-Host ""
Write-Host "Prompt size: $($userPrompt.Length) chars (~$([int]($userPrompt.Length / 4)) tokens)"
Write-Host ""

$headers = @{
    "x-api-key" = $anthropicCredential
    "anthropic-version" = "2023-06-01"
    "content-type" = "application/json"
}
$body = @{
    model = "claude-opus-4-8"
    max_tokens = 16000
    system = $systemPrompt
    messages = @(@{ role = "user"; content = $userPrompt })
    thinking = @{ type = "adaptive" }
    output_config = @{ effort = "medium" }
} | ConvertTo-Json -Depth 10

Write-Host "Calling Opus 4.8 with extended thinking (3-5 minutes)..."
$startCall = Get-Date
try {
    $r = Invoke-RestMethod -Method Post -Uri "https://api.anthropic.com/v1/messages" -Headers $headers -Body $body
    $elapsed = (Get-Date) - $startCall
    Write-Host "API response in $([math]::Round($elapsed.TotalSeconds, 1))s"
    Write-Host "tokens in: $($r.usage.input_tokens) out: $($r.usage.output_tokens)"

    $thinking = ($r.content | Where-Object { $_.type -eq "thinking" } | ForEach-Object { $_.thinking }) -join "`n`n"
    $text     = ($r.content | Where-Object { $_.type -eq "text" }     | ForEach-Object { $_.text })     -join "`n`n"
    $cost = ($r.usage.input_tokens * 15.0 + $r.usage.output_tokens * 75.0) / 1000000
    Write-Host "Cost: `$$([math]::Round($cost, 4))"

    $ts = Get-Date -Format "yyyyMMdd_HHmmss"
    $designDoc = Join-Path $OutDir "v5_topology_design_opus48_$ts.md"
    $auditJson = Join-Path $OutDir "v5_topology_design_opus48_$ts.json"

    $header = "# Cubie Topology Representation - Architectural Decision Document`n`n"
    $header += "Author of analysis: Claude Opus 4.8 (adaptive extended thinking)`n"
    $header += "Date: $(Get-Date -Format 'yyyy-MM-dd HH:mm')`n"
    $header += "Walltime: $([math]::Round($elapsed.TotalSeconds, 1))s | Tokens in/out: $($r.usage.input_tokens)/$($r.usage.output_tokens) | Cost: `$$([math]::Round($cost,4))`n`n---`n`n"

    if ($thinking -and $thinking.Length -gt 0) {
        $header += "## Opus 4.8 internal reasoning (extended thinking blocks)`n`n"
        $header += "<details><summary>Click to expand the full reasoning trace ($($thinking.Length) chars)</summary>`n`n"
        $header += $thinking
        $header += "`n`n</details>`n`n---`n`n"
    }
    $header += "## Final architectural decision document`n`n" + $text

    Set-Content -Path $designDoc -Value $header -Encoding UTF8
    Write-Host ""
    Write-Host "Design doc: $designDoc"

    $audit = @{
        model = "claude-opus-4-8"
        timestamp = (Get-Date -Format "o")
        walltime_sec = [math]::Round($elapsed.TotalSeconds, 2)
        usage = $r.usage
        cost_usd = [math]::Round($cost, 4)
        thinking_chars = $thinking.Length
        response_chars = $text.Length
        prompt_chars = $userPrompt.Length
    } | ConvertTo-Json -Depth 8
    Set-Content -Path $auditJson -Value $audit -Encoding UTF8
    Write-Host "Audit JSON: $auditJson"
} catch {
    Write-Host "ERROR:" -ForegroundColor Red
    Write-Host $_.ErrorDetails.Message
}
