#!/usr/bin/env bash
# Continuity pre-commit validation
# Validates JSON files and detects significant changes before commit.
# Self-contained — no global dependencies required.

set -euo pipefail

# Only run in Continuity projects
CONTINUITY_DIR="$(git rev-parse --show-toplevel 2>/dev/null)/.continuity"
if [ ! -d "$CONTINUITY_DIR" ]; then
  exit 0
fi

ERRORS=0

# Validate package.json if staged
if git diff --cached --name-only | grep -q '^package\.json$'; then
  if [ -f "package.json" ]; then
    if ! node -e "JSON.parse(require('fs').readFileSync('package.json','utf8'))" 2>/dev/null; then
      echo "Continuity pre-commit: ERROR — package.json is not valid JSON"
      ERRORS=1
    fi
  fi
fi

# Validate decisions.json if it exists
DECISIONS_FILE="$CONTINUITY_DIR/decisions.json"
if [ -f "$DECISIONS_FILE" ]; then
  if ! node -e "
    const d = JSON.parse(require('fs').readFileSync(process.argv[1],'utf8'));
    if (!Array.isArray(d)) { process.exit(1); }
  " "$DECISIONS_FILE" 2>/dev/null; then
    echo "Continuity pre-commit: ERROR — .continuity/decisions.json is corrupt (not a valid JSON array)"
    ERRORS=1
  fi
fi

if [ "$ERRORS" -ne 0 ]; then
  exit 1
fi

# Validate SidebarProvider command integration if staged
SIDEBAR_FILE="src/services/SidebarProvider.ts"
if git diff --cached --name-only | grep -q "$SIDEBAR_FILE"; then
  if [ -f "$SIDEBAR_FILE" ]; then
    # Get the staged content
    STAGED_CONTENT=$(git diff --cached --unified=999999 "$SIDEBAR_FILE")

    # Extract case statements
    CASES=$(echo "$STAGED_CONTENT" | grep -o "case '[^']*':" | sed "s/case '//g" | sed "s/'://g" | sort -u)

    # Check each case has a handler
    for case_name in $CASES; do
      # Case skip list — these are handled internally or don't require executeCommand
      case "$case_name" in
        "ready"|"refresh"|"exportDecisions"|"viewMetrics"|"viewConvergence"|"toggleUIMode"|"unprotectFile"|\
        "showCostDetails"|"setTokenLimit"|"resetSessionCounter"|"setSessionGoal"|"activateLicense"|\
        "shareEmailFor5More"|"setMCPProfile"|"copyDecisionAsText"|"exportDecisionMarkdown"|\
        "teamRefresh"|"teamSyncNow"|"sidebarTabSwitched"|"reportIssue")
          continue
          ;;
      esac

      # Verify executeCommand is called for this case
      if ! echo "$STAGED_CONTENT" | grep -A 10 "case '$case_name'" | grep -q "executeCommand"; then
        echo "Continuity pre-commit: WARNING — Sidebar case '$case_name' may not call executeCommand"
      fi
    done
  fi
fi

# Detect significant changes and write pending.json hint for post-commit hook
STAGED_FILES="$(git diff --cached --name-only)"
SIGNIFICANT=()

while IFS= read -r file; do
  case "$file" in
    src/services/*|src/commands/*|src/views/*)
      SIGNIFICANT+=("$file")
      ;;
  esac
done <<< "$STAGED_FILES"

# Check for new files in key directories
NEW_FILES="$(git diff --cached --name-only --diff-filter=A)"
NEW_SIGNIFICANT=()
while IFS= read -r file; do
  case "$file" in
    src/services/*|src/commands/*|packages/*)
      NEW_SIGNIFICANT+=("$file")
      ;;
  esac
done <<< "$NEW_FILES"

# Write pending.json if significant changes detected
if [ ${#SIGNIFICANT[@]} -gt 3 ] || [ ${#NEW_SIGNIFICANT[@]} -gt 0 ]; then
  node -e "
    const fs = require('fs');
    const sig = process.argv[1].split(',').filter(Boolean);
    const newSig = process.argv[2].split(',').filter(Boolean);
    const hint = {
      significantChanges: {
        modifiedArchitecturalFiles: sig,
        newArchitecturalFiles: newSig,
        timestamp: new Date().toISOString()
      }
    };
    fs.writeFileSync(process.argv[3], JSON.stringify(hint));
  " "$(IFS=,; echo "${SIGNIFICANT[*]:-}")" "$(IFS=,; echo "${NEW_SIGNIFICANT[*]:-}")" "$CONTINUITY_DIR/pending.json"
fi

exit 0
