#!/usr/bin/env bash
# Nova NORTH_STAR diff-check (REQ-204).
#
# Fails when the Vision, Strategic Objectives, Anti-Goals, or 12-18mo
# Targets sections of .ciagent/NORTH_STAR.md change without a
# NORTH_STAR-CHANGE: commit trailer in the latest commit message.
#
# Usage: bash scripts/check_north_star_diff.sh
# Returns 0 on pass, 1 on fail.

set -euo pipefail

NORTH_STAR=".ciagent/NORTH_STAR.md"
SECTIONS_REGEX='^## (Vision|Strategic Objectives|Anti-Goals|12.*18 Month Targets)'

if [ ! -f "$NORTH_STAR" ]; then
    echo "WARN: $NORTH_STAR not found — skipping diff-check"
    exit 0
fi

# Get the diff of NORTH_STAR.md in the latest commit
DIFF=$(git diff HEAD~1 -- "$NORTH_STAR" 2>/dev/null || true)

if [ -z "$DIFF" ]; then
    # No changes to NORTH_STAR.md — pass
    exit 0
fi

# Check if any of the strategic sections changed
SECTION_CHANGES=$(echo "$DIFF" | grep -E '^\+## (Vision|Strategic Objectives|Anti-Goals|12.*18 Month Targets)' || true)
LINE_CHANGES=$(echo "$DIFF" | grep -E '^[+-]' | grep -v '^[+-]{3}' | head -50 || true)

# Simple heuristic: if lines under the strategic sections changed
CHANGED_SECTIONS=""
CURRENT_SECTION=""
while IFS= read -r line; do
    case "$line" in
        "+## Vision"*) CURRENT_SECTION="Vision" ;;
        "+## Strategic Objectives"*) CURRENT_SECTION="Strategic Objectives" ;;
        "+## Anti-Goals"*) CURRENT_SECTION="Anti-Goals" ;;
        "+## 12"*) CURRENT_SECTION="12-18mo Targets" ;;
        "+## "*) CURRENT_SECTION="" ;;
    esac
    if [ -n "$CURRENT_SECTION" ] && [ -n "$line" ] && [[ "$line" == +* ]] && [[ "$line" != "+## "* ]]; then
        CHANGED_SECTIONS="$CHANGED_SECTIONS $CURRENT_SECTION"
    fi
done <<< "$DIFF"

if [ -z "$CHANGED_SECTIONS" ]; then
    # No strategic section changes — pass
    exit 0
fi

# Check for the NORTH_STAR-CHANGE: commit trailer
COMMIT_MSG=$(git log -1 --format='%B')
if echo "$COMMIT_MSG" | grep -q "NORTH_STAR-CHANGE:"; then
    echo "OK: NORTH_STAR strategic sections changed with NORTH_STAR-CHANGE: trailer"
    exit 0
fi

echo "FAIL: NORTH_STAR strategic sections changed without NORTH_STAR-CHANGE: commit trailer"
echo "Changed sections:$CHANGED_SECTIONS"
echo "Add 'NORTH_STAR-CHANGE: <description>' to the commit message and re-commit."
exit 1