#!/usr/bin/env bash
set -euo pipefail

BASE="${1:-/mnt/bigstor/www/usecases}"
TARGET="$BASE/build_about_page.py"
VERSION="$BASE/data/version.json"
STAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP_TARGET="$TARGET.bak-contact-label-$STAMP"
BACKUP_VERSION="$VERSION.bak-contact-label-$STAMP"

[[ -f "$TARGET" ]] || { echo "ERROR: missing $TARGET" >&2; exit 2; }
[[ -f "$VERSION" ]] || { echo "ERROR: missing $VERSION" >&2; exit 2; }
cp -a "$TARGET" "$BACKUP_TARGET"
cp -a "$VERSION" "$BACKUP_VERSION"

rollback() {
  echo "ERROR: patch failed; restoring backups" >&2
  cp -a "$BACKUP_TARGET" "$TARGET"
  cp -a "$BACKUP_VERSION" "$VERSION"
}
trap rollback ERR

python3 - "$TARGET" <<'PY'
from pathlib import Path
import sys
p=Path(sys.argv[1])
s=p.read_text(encoding='utf-8')

# Signature
old='''    contact_email: str,\n    release_notes_html: str,'''
new='''    contact_email: str,\n    contact_label: str,\n    release_notes_html: str,'''
if old in s:
    s=s.replace(old,new,1)
elif '    contact_label: str,\n' not in s:
    raise SystemExit('ERROR: build_version_block signature anchor not found')

# Escaped label
old='''    email_e = html.escape(contact_email, quote=True)\n'''
new='''    email_e = html.escape(contact_email, quote=True)\n    contact_label_e = html.escape(contact_label, quote=True)\n'''
if 'contact_label_e = html.escape(contact_label' not in s:
    if old not in s: raise SystemExit('ERROR: email escape anchor not found')
    s=s.replace(old,new,1)

# Visible link text only
old='<span class="version-value"><a href="mailto:{email_e}">{email_e}</a></span>'
new='<span class="version-value"><a href="mailto:{email_e}">{contact_label_e}</a></span>'
if old in s:
    s=s.replace(old,new,1)
elif new not in s:
    raise SystemExit('ERROR: contact link anchor not found')

# Read optional metadata, safe fallback to email
old='''    contact_email = validate_email(required_text(metadata, "contact_email"))\n'''
new='''    contact_email = validate_email(required_text(metadata, "contact_email"))\n    contact_label = str(metadata.get("contact_label", contact_email)).strip() or contact_email\n'''
if 'contact_label = str(metadata.get("contact_label"' not in s:
    if old not in s: raise SystemExit('ERROR: contact metadata anchor not found')
    s=s.replace(old,new,1)

# Pass to builder
old='''        contact_email=contact_email,\n        release_notes_html=release_notes_to_html(release_notes),'''
new='''        contact_email=contact_email,\n        contact_label=contact_label,\n        release_notes_html=release_notes_to_html(release_notes),'''
if '        contact_label=contact_label,\n' not in s:
    if old not in s: raise SystemExit('ERROR: build_version_block call anchor not found')
    s=s.replace(old,new,1)

p.write_text(s,encoding='utf-8')
print('PATCHED:',p)
PY

python3 - "$VERSION" <<'PY'
from pathlib import Path
import json,sys
p=Path(sys.argv[1])
data=json.loads(p.read_text(encoding='utf-8'))
data['contact_label']='Contact NCRC'
p.write_text(json.dumps(data,indent=2,ensure_ascii=False)+'\n',encoding='utf-8')
print('UPDATED:',p)
PY

python3 -m py_compile "$TARGET"
python3 -m json.tool "$VERSION" >/dev/null
python3 "$TARGET" --check

trap - ERR
printf '\nPATCH COMPLETE\n'
printf '  generator backup: %s\n' "$BACKUP_TARGET"
printf '  version backup  : %s\n' "$BACKUP_VERSION"
