#!/usr/bin/env nu
# Generated by: typedialog form reflection/forms/supersede_adr.ncl
# Superseding: {{ old_adr_id }} → {{ new_adr_id }}
# Reason: {{ supersession_reason }} — {{ supersession_note }}

let old_file = "{{ old_adr_file }}"
let new_file = "{{ new_adr_file }}"
let old_id   = "{{ old_adr_id }}"
let new_id   = "{{ new_adr_id }}"

# ── Step 1: Patch old ADR ────────────────────────────────────────────────────
# Read source, replace status and add superseded_by.
# Uses sed — safe only for the exact patterns below.

let old_src = open $old_file

# Verify current status is Accepted before patching
let current_status = (nickel export $old_file | from json | get status)
if $current_status != "Accepted" {
  error make { msg: $"Expected status = Accepted in ($old_file), got ($current_status)" }
}

$old_src
  | str replace --regex "status\\s*=\\s*'Accepted" $"status = 'Superseded"
  | str replace --regex "(status\\s*=\\s*'Superseded,)" $"$1\n  superseded_by = \"($new_id)\","
  | save --force $old_file

print $"✓ ($old_file): status = Superseded, superseded_by = ($new_id)"

# ── Step 2: Verify old ADR exports ───────────────────────────────────────────

do { nickel export $old_file | ignore } | complete | if $in.exit_code != 0 {
  error make { msg: $"($old_file) failed to export after patch — revert and fix manually" }
}
print $"✓ ($old_file) exports cleanly"

# ── Step 3: Verify new ADR exports ───────────────────────────────────────────

do { nickel export $new_file | ignore } | complete | if $in.exit_code != 0 {
  error make { msg: $"($new_file) failed to export — fix before committing" }
}

let new_status = (nickel export $new_file | from json | get status)
print $"✓ ($new_file) exports cleanly with status = ($new_status)"

# ── Step 4: Verify supersession chain ────────────────────────────────────────

let new_supersedes = (nickel export $new_file | from json | get supersedes? | default "")
if $new_supersedes != $old_id {
  print $"⚠ ($new_file) does not have supersedes = \"($old_id)\" — chain integrity broken"
  print $"  Add: supersedes = \"($old_id)\" to ($new_file) before committing"
} else {
  print $"✓ Supersession chain intact: ($new_id).supersedes = ($old_id)"
}

# ── Step 5: Commit ────────────────────────────────────────────────────────────

print ""
print "Run when ready to commit:"
print $"  git add ($old_file) ($new_file)"
print $"  git commit -m \"adr: ($old_id) superseded by ($new_id) — {{ supersession_note }}\""
