#!/usr/bin/env bash
# generate-housekeeping-release-ticket.sh
#
# Writes a housekeeping release-ticket stub for a bare-date release
# (`v2026.06.04` etc.). Synced into the consumer's `scripts/` by
# `devaudit update`; invoked from `compliance-evidence.yml` after
# `derive-release-version.sh` when the version pattern is bare-date AND
# no ticket file already exists.
#
# Usage:
#   bash scripts/generate-housekeeping-release-ticket.sh <version> > <out>
#
# Where <version> is the bare-date version (e.g. `v2026.06.04`) and
# <out> is the target path (typically `compliance/pending-releases/
# RELEASE-TICKET-<version>.md`).
#
# The stub carries:
# - Frontmatter with version + generated_at + last_reviewed_at (defaults
#   to today; operator updates on sign-off)
# - Commit summaries since the previous release tag (or last 20 commits
#   if no prior tag exists)
# - An operator sign-off block with `REPLACE — …` markers the operator
#   must fill in before merging the auto-PR
#
# Companion to `generate-security-summary.sh`. Both are invoked together
# by the CI workflow.
#
# DevAudit-Installer#116 WS3.

set -euo pipefail

VERSION="${1:-}"
if [ -z "$VERSION" ]; then
  echo "usage: $(basename "$0") <version>" >&2
  exit 2
fi

# Validate bare-date pattern (matches `classifyReleaseShape` in META-COMPLY).
if ! [[ "$VERSION" =~ ^v[0-9]{4}\.[0-9]{2}\.[0-9]{2}(\.[0-9]+)?$ ]]; then
  echo "error: '$VERSION' is not a bare-date version (expected vYYYY.MM.DD[.N])" >&2
  exit 2
fi

TODAY=$(date -u +%Y-%m-%d)

# Escape freeform table-cell content so markdownlint does not misparse
# literal pipes as extra columns in generated release evidence.
markdown_table_cell() {
  printf '%s' "${1:-}" | perl -0pe 's/(?<!\\)\|/\\|/g'
}

# Last 20 commits with subject lines. Skip the version-deriver fallback
# from itself (avoid recursion if this script is re-run on a branch
# that already includes its own auto-commit).
COMMIT_LINES=$(git log -20 --pretty=format:'- `%h` %s' 2>/dev/null \
  | grep -v 'chore: housekeeping release-ticket stub' \
  | head -15)
if [ -z "$COMMIT_LINES" ]; then
  COMMIT_LINES="- _(no commits found in `git log` — this stub was generated outside a git context)_"
fi

cat <<EOF
---
version: "$VERSION"
release_shape: housekeeping
generated_at: "$TODAY"
last_reviewed_at: "$TODAY"
generated_by: "generate-housekeeping-release-ticket.sh (DevAudit-Installer#116)"
---

> ⚠️ **AUTO-GENERATED STUB — REPLACE BEFORE MERGE**
>
> This release ticket was auto-generated by CI when develop received a
> housekeeping push (no \`REQ-XXX\` in commit subjects, version derived
> as bare-date \`$VERSION\`).
>
> **The operator must:**
> 1. Confirm the **Summary** below describes the actual intent of these
>    commits — replace the placeholder if the auto-summary is generic.
> 2. Fill in the **Sign-off** block with the operator's name + date +
>    risk assessment.
> 3. Merge this PR. The next \`compliance-evidence.yml\` run will upload
>    this file as \`release_artifact\` evidence, satisfying the
>    portal's release-ticket completeness check.

# Release Ticket: $VERSION (housekeeping)

**Status:** TESTED - PENDING SIGN-OFF
**Date:** $TODAY
**Release Shape:** Housekeeping (bare-date, no REQ tag)
**Version:** $VERSION

---

## Summary

REPLACE — one or two sentences describing what these housekeeping commits delivered. Examples: *"Documentation refresh for the v0.1.39 governance changes; no code paths touched."* / *"Dependency bumps (vitest 4.0.5 → 4.0.6, prettier 4.3.0 → 4.3.1) caught by Dependabot; no behavioural change."* / *"CI workflow housekeeping: retry-on-flake threshold raised, runner image pinned."*

## Commits in this release

$COMMIT_LINES

## Risk Assessment

REPLACE — confirm risk class for this release (typically LOW for housekeeping):

- [ ] **LOW** — documentation, dependency bumps, CI tweaks, internal refactors. No user-visible behaviour change.
- [ ] **MEDIUM** — touches code paths an end-user reaches; user-visible change is small and well-contained.
- [ ] **HIGH** — should not be a housekeeping release. If this is checked, **stop and re-tag the commits with \`REQ-XXX\`** so the release is tracked properly.

## Test Evidence

> When editing any markdown table below, escape literal pipe characters in cell
> content as \`\\|\` so RTM/release-evidence tables stay lint-safe.

| Test Type | Status | Source |
| --- | --- | --- |
| TypeScript | $(markdown_table_cell "$(test -f gate-outcomes.json && echo "see gate-outcomes.json" || echo "REPLACE — green / N/A")") | CI \`typecheck\` gate |
| SAST | $(markdown_table_cell "$(test -f gate-outcomes.json && echo "see gate-outcomes.json" || echo "REPLACE — green / N/A")") | CI \`SAST\` gate |
| Dependency audit | $(markdown_table_cell "$(test -f gate-outcomes.json && echo "see gate-outcomes.json" || echo "REPLACE — green / N/A")") | CI \`dependency_audit\` gate |
| E2E | $(markdown_table_cell "$(test -f gate-outcomes.json && echo "see gate-outcomes.json" || echo "REPLACE — green / N/A")") | CI \`e2e\` gate |
| Test reports | $(markdown_table_cell "$(test -f gate-outcomes.json && echo "see gate-outcomes.json" || echo "REPLACE — green / N/A")") | CI \`test_report\` gate |

> Companion artefact: \`compliance/security-summary-$VERSION.md\` (auto-generated by \`generate-security-summary.sh\` in the same workflow run; contains the SAST + dep-audit findings detail).

## Acceptance Criteria

- [x] All four compliance gates green on the CI run that produced this stub
- [x] No \`REQ-XXX\`-tagged commits in this release (housekeeping by definition)
- [ ] Operator-reviewed and signed off — see Sign-off block below

## Post-Deploy Actions

| Type | Script / Command | Target | Required | Notes |
| ------ | ----------------- | -------- | ---------- | ------- |
| — | None | — | — | Housekeeping releases typically have no post-deploy actions |

<!-- Replace the "None" row above if this release requires post-deploy work. -->

---

## Sign-off

| Role | Name | Date | Notes |
| --- | --- | --- | --- |
| Submitter | REPLACE | $TODAY | Auto-generated by CI; reviewed + edited |
| Reviewer (independent if project risk_tier ≠ low) | REPLACE | REPLACE | REPLACE |

## Audit Trail

| Date | Action | Actor | Notes |
| ------ | -------- | ------- | ------- |
| $TODAY | Stub auto-generated | devaudit-bot | Bare-date version $VERSION |
| REPLACE | Operator sign-off | REPLACE | REPLACE |
| REPLACE | Submitted for UAT review | REPLACE | Via portal |
EOF
