<#
.SYNOPSIS
  Open and edit SHIP-ATTESTATION.md without the web UI.
.DESCRIPTION
  Signing is file-based: change [ ] to [x] on lines you have personally verified.
  This script shows status, opens the file in Notepad, or toggles lines interactively.
.EXAMPLE
  .\scripts\Sign-ShipAttestation.ps1
.EXAMPLE
  .\scripts\Sign-ShipAttestation.ps1 -OpenOnly
.EXAMPLE
  .\scripts\Sign-ShipAttestation.ps1 -Lines 2,7 -Verify
#>
[CmdletBinding()]
param(
    [string]$Root = (Split-Path $PSScriptRoot -Parent),
    [switch]$OpenOnly,
    [int[]]$Lines,
    [switch]$Verify
)

if (-not (Test-Path (Join-Path $Root 'package.json'))) {
    $Root = 'K:\RHOYLLE BUSINESS EMPIRE LLC\Business Plans\PRODUCTS\DBAOps-Sovereign'
}
$attestPath = Join-Path $Root '_ship_readiness\SHIP-ATTESTATION.md'
$runbookPath = Join-Path $Root '_ship_readiness\SHIP-CLOSEOUT-RUNBOOK.md'

if (-not (Test-Path $attestPath)) {
    throw "Attestation file not found: $attestPath"
}

function Get-AttestationLines {
    Get-Content $attestPath -Encoding UTF8 | Where-Object { $_ -match '^\[[ x]\]' }
}

function Show-Status {
    $rows = Get-AttestationLines
    $done = @($rows | Where-Object { $_ -match '^\[x\]' }).Count
    $total = @($rows).Count
    Write-Host ''
    Write-Host 'SHIP ATTESTATION STATUS' -ForegroundColor Cyan
    Write-Host "File: $attestPath"
    Write-Host "Signed: $done / $total" -ForegroundColor $(if ($done -eq $total) { 'Green' } else { 'Yellow' })
    Write-Host ''
    $n = 0
    foreach ($line in $rows) {
        $n++
        $mark = if ($line -match '^\[x\]') { '[x]' } else { '[ ]' }
        $text = ($line -replace '^\[[ x]\]\s*', '').Trim()
        if ($text.Length -gt 72) { $text = $text.Substring(0, 69) + '...' }
        Write-Host ("  {0,2}. {1}  {2}" -f $n, $mark, $text)
    }
    Write-Host ''
}

function Set-LineSigned([int]$num, [bool]$signed) {
    $all = Get-Content $attestPath -Encoding UTF8
    $rows = @($all | Where-Object { $_ -match '^\[[ x]\]' })
    if ($num -lt 1 -or $num -gt $rows.Count) {
        throw "Line number must be 1-$($rows.Count)"
    }
    $target = $rows[$num - 1]
    $newMark = if ($signed) { '[x]' } else { '[ ]' }
    $body = ($target -replace '^\[[ x]\]\s*', '').Trim()
    $replacement = "$newMark $body"
    $hit = $false
    for ($i = 0; $i -lt $all.Count; $i++) {
        if (-not $hit -and $all[$i] -eq $target) {
            $all[$i] = $replacement
            $hit = $true
        }
    }
    if (-not $hit) { throw "Could not update line $num" }
    $all | Set-Content -Path $attestPath -Encoding UTF8
}

function Open-Attestation {
    Write-Host "Opening in Notepad: $attestPath" -ForegroundColor Green
    Write-Host 'Edit [ ] to [x] (lowercase x) on lines you verified. Save and close Notepad.' -ForegroundColor Gray
    Start-Process notepad.exe -ArgumentList $attestPath
}

Show-Status

if ($Lines -and $Lines.Count -gt 0) {
    foreach ($ln in $Lines) {
        Set-LineSigned -num $ln -signed $true
        Write-Host "Signed line $ln" -ForegroundColor Green
    }
    Show-Status
}
elseif (-not $OpenOnly) {
    Write-Host 'OPTIONS' -ForegroundColor Cyan
    Write-Host '  1  Open SHIP-ATTESTATION.md in Notepad (manual edit)'
    Write-Host '  2  Toggle a line by number (sign / unsign)'
    Write-Host '  3  Open closeout runbook (what each line means)'
    Write-Host '  4  Run proof harnesses (license + uninstall)'
    Write-Host '  5  Re-run ship gate (verify:ship-gate)'
    Write-Host '  Q  Quit'
    Write-Host ''
    $choice = Read-Host 'Choice'
    switch ($choice.ToUpper()) {
        '1' { Open-Attestation; Read-Host 'Press Enter after saving Notepad' }
        '2' {
            $ln = [int](Read-Host 'Line number to toggle (1-8)')
            $rows = Get-AttestationLines
            $current = $rows[$ln - 1] -match '^\[x\]'
            Set-LineSigned -num $ln -signed (-not $current)
            Show-Status
        }
        '3' {
            if (Test-Path $runbookPath) { Start-Process notepad.exe -ArgumentList $runbookPath }
            else { Write-Host "Runbook not found: $runbookPath" -ForegroundColor Yellow }
        }
        '4' {
            Push-Location $Root
            powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Root 'scripts\Prove-LicenseEnforcement.ps1')
            powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Root 'scripts\Prove-Uninstall.ps1')
            Pop-Location
        }
        '5' { $Verify = $true }
        default { }
    }
}
else {
    Open-Attestation
}

if ($Verify) {
    Write-Host ''
    Write-Host 'Running npm run verify:ship-gate ...' -ForegroundColor Cyan
    Push-Location $Root
    npm run verify:ship-gate
    Pop-Location
}

Show-Status
