#!/usr/bin/env bash
# validate-problems.sh
# Validates that all DSA problem files contain the required sections.

set -euo pipefail

# ANSI color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Required sections (standard 16 headings or equivalents)
REQUIRED_SECTIONS=(
  "At a Glance|Quick Identifier"
  "Problem (one-liner)|Quick Sights"
  "Core Basics|Concept Explanation"
  "Understanding"
  "Memory Hooks"
  "Recognition Cues"
  "Study Pattern (SDE3+)"
  "Diagram"
  "Approaches"
  "Optimal Solution"
  "Walkthrough"
  "Edge Cases"
  "Pitfalls"
  "Similar Problems"
  "Variants"
  "Mind-Map Tags"
)

validate_file() {
  local file="$1"
  local errors=0

  echo -e "${YELLOW}Validating file: ${file}${NC}"

  # 1. Check all required sections are present
  for section in "${REQUIRED_SECTIONS[@]}"; do
    if ! grep -q -E "^## (${section})" "$file"; then
      echo -e "  ${RED}❌ Missing section: ## ${section}${NC}"
      errors=$((errors + 1))
    fi
  done

  # 2. Check if Diagram contains a Mermaid block
  if grep -q "^## Diagram" "$file"; then
    # Look at the lines following ## Diagram to see if they contain a mermaid code fence
    if ! sed -n '/^## Diagram/,/^##/p' "$file" | grep -q '```mermaid'; then
      echo -e "  ${RED}❌ Diagram section does not contain a \`\`\`mermaid\` block${NC}"
      errors=$((errors + 1))
    fi
  fi

  if [ "$errors" -eq 0 ]; then
    echo -e "  ${GREEN}✓ All checks passed${NC}"
    return 0
  else
    echo -e "  ${RED}✗ Found ${errors} error(s)${NC}"
    return 1
  fi
}

main() {
  local target_dir="${1:-content/core-docs/dsa/topics}"

  if [ ! -d "$target_dir" ]; then
    echo -e "${RED}Error: Target directory '${target_dir}' does not exist.${NC}"
    exit 1
  fi

  echo "Scanning for markdown files under '${target_dir}'..."
  local files
  # Find all problem files (excluding index, README, meta etc.)
  mapfile -t files < <(find "$target_dir" -name "*.md" -not -name "README.md" -not -name "meta.md" -not -path "*/docs/*")

  if [ ${#files[@]} -eq 0 ]; then
    echo -e "${YELLOW}No problem files found.${NC}"
    exit 0
  fi

  local failed=0
  for f in "${files[@]}"; do
    if ! validate_file "$f"; then
      failed=$((failed + 1))
    fi
  done

  echo -e "\n=== Validation Summary ==="
  if [ "$failed" -eq 0 ]; then
    echo -e "${GREEN}All ${#files[@]} files are valid!${NC}"
    exit 0
  else
    echo -e "${RED}${failed} file(s) failed validation checks.${NC}"
    exit 1
  fi
}

main "$@"
