#!/usr/bin/env bash
# Agent build verification — run from project root after Phase 5 BUILD
# Prefer: npx cfm-sdk verify-build
# See: 00-integration/phase-5-6-build-gate.md
#
# Docs-only model: this gate checks the IMMUTABLE SPINE (data / logic / SDK
# integration) of the agent-authored components. Styling is free — there are NO
# token / class / bundle checks here. Hardcoded colors are allowed.
set -euo pipefail

echo "=== CFM Survey SDK — Core verify ==="

STUB_MATCHES=$(grep -r "not yet implemented" src/ components/ app/ 2>/dev/null || true)
if [ -n "$STUB_MATCHES" ]; then
  echo "FAIL: Stub placeholder text found:"
  echo "$STUB_MATCHES"
  exit 1
fi
echo "OK: No stub placeholder text"

INTERNAL_IMPORTS=$(grep -rE "@explorer02/cfm-survey-sdk/src|@repo/sdk/src" src/ components/ app/ 2>/dev/null || true)
if [ -n "$INTERNAL_IMPORTS" ]; then
  echo "FAIL: Internal SDK imports found (import from the package root only):"
  echo "$INTERNAL_IMPORTS"
  exit 1
fi
echo "OK: No internal SDK imports"

verify_framework_config() {
  local -a FIXES=()
  local FRAMEWORK="unknown"
  local SDK_PKG=""
  local AWS_DEPLOY="0"

  if [ ! -f "package.json" ]; then
    echo "FAIL: package.json missing — cannot verify framework scaffold"
    exit 1
  fi

  if grep -qE '"next"[[:space:]]*:' package.json; then
    FRAMEWORK="nextjs"
  elif grep -qE '"vite"[[:space:]]*:' package.json; then
    FRAMEWORK="vite"
  elif grep -qE '"react-scripts"[[:space:]]*:' package.json; then
    FRAMEWORK="cra"
  fi

  if grep -qE '"@explorer02/cfm-survey-sdk"[[:space:]]*:' package.json; then
    SDK_PKG="@explorer02/cfm-survey-sdk"
  elif grep -qE '"@repo/sdk"[[:space:]]*:' package.json; then
    SDK_PKG="@repo/sdk"
  fi

  if [ -f "./survey-ui-config.json" ] && grep -qE '"target"[[:space:]]*:[[:space:]]*"aws"' ./survey-ui-config.json; then
    AWS_DEPLOY="1"
  fi

  if [ "$FRAMEWORK" = "nextjs" ]; then
    NEXT_CONFIG=""
    for candidate in next.config.js next.config.mjs next.config.ts; do
      if [ -f "$candidate" ]; then NEXT_CONFIG="$candidate"; break; fi
    done
    if [ -z "$NEXT_CONFIG" ]; then
      FIXES+=("Create next.config.js with transpilePackages: ['${SDK_PKG:-@explorer02/cfm-survey-sdk}'] — see setup/nextjs.md")
    else
      if ! grep -q "transpilePackages" "$NEXT_CONFIG"; then
        FIXES+=("Add transpilePackages: ['${SDK_PKG:-@explorer02/cfm-survey-sdk}'] to $NEXT_CONFIG")
      elif [ -n "$SDK_PKG" ] && ! grep -q "$SDK_PKG" "$NEXT_CONFIG"; then
        FIXES+=("Add '$SDK_PKG' to transpilePackages in $NEXT_CONFIG")
      fi
      if [ "$AWS_DEPLOY" = "1" ]; then
        if ! grep -qE "output[[:space:]]*:[[:space:]]*['\"]export['\"]" "$NEXT_CONFIG"; then
          FIXES+=("Add output: 'export' to $NEXT_CONFIG for AWS deploy — see setup/nextjs-aws-export.md")
        fi
        if ! grep -qE "assetPrefix[[:space:]]*:[[:space:]]*['\"]\.\/['\"]" "$NEXT_CONFIG"; then
          FIXES+=("Add assetPrefix: './' to $NEXT_CONFIG for AWS deploy")
        fi
      fi
    fi

    SURVEY_PAGE_LOCAL=""
    for candidate in src/components/SurveyPage.tsx components/SurveyPage.tsx app/components/SurveyPage.tsx; do
      if [ -f "$candidate" ]; then SURVEY_PAGE_LOCAL="$candidate"; break; fi
    done
    if [ -n "$SURVEY_PAGE_LOCAL" ] && ! head -n 3 "$SURVEY_PAGE_LOCAL" | grep -q "'use client'"; then
      FIXES+=("Add 'use client' to $SURVEY_PAGE_LOCAL — required for Next.js App Router")
    fi
  fi

  if [ "$FRAMEWORK" = "vite" ] && [ "$AWS_DEPLOY" = "1" ]; then
    VITE_CONFIG=""
    for candidate in vite.config.ts vite.config.js vite.config.mjs; do
      if [ -f "$candidate" ]; then VITE_CONFIG="$candidate"; break; fi
    done
    if [ -n "$VITE_CONFIG" ] && ! grep -qE "base[[:space:]]*:[[:space:]]*['\"]\.\/['\"]" "$VITE_CONFIG"; then
      FIXES+=("Add base: './' to $VITE_CONFIG for AWS deploy — see setup/vite.md")
    elif [ -z "$VITE_CONFIG" ]; then
      FIXES+=("Create vite.config.ts with base: './' for AWS deploy")
    fi
  fi

  if [ "${#FIXES[@]}" -gt 0 ]; then
    echo "FAIL: Framework scaffold incomplete ($FRAMEWORK) — fix all items before build:"
    for fix in "${FIXES[@]}"; do
      echo "  - $fix"
    done
    exit 1
  fi

  if [ "$FRAMEWORK" != "unknown" ]; then
    echo "OK: Framework scaffold verified ($FRAMEWORK)"
  else
    echo "WARN: Framework not detected from package.json — skipping scaffold checks"
  fi
}

verify_framework_config

# --- Logic layer: dispatcher must cover every question type, no stubs, no subType ---
REQUIRED_TYPES=(MCQ TEXTFIELD NPS_SCALE CFM_MATRIX CSAT_MATRIX RATING_MATRIX SLIDER_MATRIX FILE_UPLOAD TEXT_AND_MEDIA HEATMAP RANK_ORDER)
SRC_DIRS=""
for d in src components app; do [ -d "$d" ] && SRC_DIRS="$SRC_DIRS $d"; done

if [ -z "$SRC_DIRS" ]; then
  echo "WARN: no src/components/app directory found — skipping dispatcher coverage"
else
  for t in "${REQUIRED_TYPES[@]}"; do
    if ! grep -rqE "QUESTION_TYPE\.${t}\b|['\"]${t}['\"]" $SRC_DIRS 2>/dev/null; then
      echo "FAIL: No handling found for question type: ${t} — author a dispatcher branch (no stubs)"
      exit 1
    fi
  done
  echo "OK: All 11 question types are handled in source"

  if grep -rq "subType" $SRC_DIRS 2>/dev/null; then
    echo "FAIL: Legacy subType routing found — use flat question.type literals"
    exit 1
  fi
  echo "OK: Flat question.type routing (no subType)"

  # RANK_ORDER wiring: dnd-kit dependency + rank actions
  if grep -rqE "RANK_ORDER\b|RankOrder" $SRC_DIRS 2>/dev/null; then
    if ! grep -q "@dnd-kit/core" package.json 2>/dev/null; then
      echo "FAIL: @dnd-kit/core missing from package.json (required for RANK_ORDER)"
      exit 1
    fi
    if ! grep -rqE "RANK_ORDER_SET_RANK|RANK_ORDER_REORDER" $SRC_DIRS 2>/dev/null; then
      echo "FAIL: RANK_ORDER must dispatch RANK_ORDER_SET_RANK / RANK_ORDER_REORDER via onAction"
      exit 1
    fi
    echo "OK: RANK_ORDER wired with @dnd-kit + rank actions"
  fi

  # Answer-logic must come from hook-prepared currentQuestions, not removed SDK helpers
  if grep -rqE "getVisibleMcqOptionsForAnswers|getVisibleMatrixItemsForAnswers|resolveSurveyQuestionPlaceholders" $SRC_DIRS 2>/dev/null; then
    echo "FAIL: Do not use removed visibility/placeholder helpers — render hook-prepared state.currentQuestions"
    exit 1
  fi
  echo "OK: No removed SDK visibility/placeholder helpers"
fi

# --- SDK integration: SurveyPage phase router, START, navCta, env instanceId ---
SURVEY_PAGE=""
for candidate in src/components/SurveyPage.tsx components/SurveyPage.tsx app/components/SurveyPage.tsx; do
  if [ -f "$candidate" ]; then SURVEY_PAGE="$candidate"; break; fi
done

if [ -n "$SURVEY_PAGE" ]; then
  if ! grep -qE "type: 'START'|type: \"START\"" "$SURVEY_PAGE"; then
    echo "FAIL: SurveyPage must dispatch onAction({ type: 'START' }) for intro — see build-gate/intro-start-gate.md"
    exit 1
  fi
  echo "OK: SurveyPage wires intro START action"

  if grep -qE "phase\.kind === ['\"]intro['\"]|kind === ['\"]intro['\"]" "$SURVEY_PAGE"; then
    if ! grep -q "IntroPage" "$SURVEY_PAGE"; then
      echo "FAIL: SurveyPage intro phase must render an intro page component — not inline header/description only"
      exit 1
    fi
    echo "OK: SurveyPage intro branch uses an IntroPage component"
  fi

  if ! grep -qE "navCta|backLabel|primaryLabel" "$SURVEY_PAGE"; then
    echo "FAIL: SurveyPage must use state.navCta for content Back/Next labels — see cta-handling.md"
    exit 1
  fi
  echo "OK: SurveyPage uses navCta for content navigation labels"

  if grep -qE "YOUR_INSTANCE_ID_HERE|SURVEY_INSTANCE_ID = '" "$SURVEY_PAGE" 2>/dev/null; then
    echo "FAIL: SurveyPage must read instanceId from env — not a hardcoded JWT; see instance-id-quick-wire.md"
    exit 1
  fi
  ENV_WIRED=$(grep -rE "getSurveyInstanceId|surveyInstanceId|VITE_CFM_INSTANCE_ID|NEXT_PUBLIC_CFM_INSTANCE_ID" src/ components/ app/ lib/ 2>/dev/null || true)
  if [ -z "$ENV_WIRED" ]; then
    echo "FAIL: No env-based instanceId wiring found — read the JWT from env; see instance-id-quick-wire.md"
    exit 1
  fi
  echo "OK: instanceId reads from env (not hardcoded JWT)"
fi

# --- Intro page: blocking Start gate (single semantic hook, styling free) ---
INTRO_PAGE=""
for candidate in src/components/IntroPage.tsx components/IntroPage.tsx app/components/IntroPage.tsx; do
  if [ -f "$candidate" ]; then INTRO_PAGE="$candidate"; break; fi
done

if [ -z "$INTRO_PAGE" ]; then
  echo "FAIL: IntroPage.tsx missing — author an intro page with a Start button (onAction START)"
  exit 1
fi
echo "OK: IntroPage.tsx present ($INTRO_PAGE)"

if ! grep -qE "onClick=\{onStart\}|onClick=\{\s*onStart\s*\}" "$INTRO_PAGE"; then
  echo "FAIL: IntroPage must wire the Start button with onClick={onStart} — see build-gate/intro-start-gate.md"
  exit 1
fi
if grep -qE '\{showStart &&|showStart &&' "$INTRO_PAGE"; then
  echo "FAIL: IntroPage must always render the Start button — remove showStart conditional"
  exit 1
fi
if ! grep -q "data-cfm-btn-start" "$INTRO_PAGE"; then
  echo "FAIL: IntroPage must mark the Start button with data-cfm-btn-start (intro-start gate hook)"
  exit 1
fi
echo "OK: IntroPage Start button wired (always rendered)"

if grep -qE "import Header|<Header|from '@/components/Header'|from \"@/components/Header\"" "$INTRO_PAGE"; then
  echo "FAIL: IntroPage must not render Header — intro phase has no chrome"
  exit 1
fi
if grep -qE "import Footer|<Footer|from '@/components/Footer'|from \"@/components/Footer\"" "$INTRO_PAGE"; then
  echo "FAIL: IntroPage must not render Footer — intro phase has no chrome"
  exit 1
fi
echo "OK: IntroPage has no Header/Footer chrome"

# --- Special pages must not render chrome ---
END_PAGE=""
for candidate in src/components/EndPage.tsx components/EndPage.tsx app/components/EndPage.tsx; do
  if [ -f "$candidate" ]; then END_PAGE="$candidate"; break; fi
done
if [ -n "$END_PAGE" ]; then
  if grep -qE "import Header|<Header|from '@/components/Header'" "$END_PAGE"; then
    echo "FAIL: EndPage must not render Header — terminal phases have no chrome"
    exit 1
  fi
  if grep -qE "import Footer|<Footer|from '@/components/Footer'" "$END_PAGE"; then
    echo "FAIL: EndPage must not render Footer — terminal phases have no chrome"
    exit 1
  fi
  echo "OK: EndPage has no Header/Footer chrome"
fi

echo "Running npm run build..."
npm run build

echo "=== Core verify passed — CFM_NEXT_STEP=ASK_DEPLOY ==="
echo "Deploy prompt is printed by npx cfm-sdk verify-build (TypeScript CLI)."
