#!/usr/bin/env bash
# 🧭 Jemy-dev OS — Project Context Snapshot v7.3 (Neon Gradient HUD Edition)
# -----------------------------------------------------------------
# ✅ Auto-create Docs/snapshots if missing
# ✅ HUD-style gradient logger (blue → violet)
# ✅ Safe CI / Gemini integration
# -----------------------------------------------------------------

set -e

# ---------- CLI Colors ----------
if [ -t 1 ]; then
  BOLD=$(tput bold); RESET=$(tput sgr0)
  CYAN=$(tput setaf 6); GREEN=$(tput setaf 2); BLUE=$(tput setaf 4)
  MAGENTA=$(tput setaf 5); VIOLET=$(tput setaf 13); GREY=$(tput setaf 8)
else
  BOLD=""; RESET=""; CYAN=""; GREEN=""; BLUE=""; MAGENTA=""; VIOLET=""; GREY=""
fi
DIVIDER="${CYAN}────────────────────────────────────────${RESET}"

# ---------- Defaults ----------
MODE="cli"
DEPTH=3
SINCE="7d"
USE_GIT=true
LOG=true
FAST=false
TARGET_DIR="Docs/snapshots"

# ---------- Parse arguments ----------
while [[ $# -gt 0 ]]; do
  case "$1" in
    --json) MODE="json"; shift ;;
    --depth) DEPTH="$2"; shift 2 ;;
    --since) SINCE="$2"; shift 2 ;;
    --no-git) USE_GIT=false; shift ;;
    --no-log) LOG=false; shift ;;
    --fast) FAST=true; shift ;;
    *)
      echo "⚠️ Unknown option: $1"
      echo "Usage: $0 [--json] [--depth N] [--since {3d|12h|1w}] [--no-git] [--no-log] [--fast]"
      exit 1
      ;;
  esac
done

# ---------- Helpers ----------
escape_json() { printf '%s' "$1" | sed ':a;N;$!ba;s/\\/\\\\/g; s/"/\\"/g; s/\n/\\n/g'; }

since_to_minutes() {
  local val="$1"
  case "$val" in
    *h) awk "BEGIN {printf \"%d\", ${val%h}*60}" ;;
    *d) awk "BEGIN {printf \"%d\", ${val%d}*1440}" ;;
    *w) awk "BEGIN {printf \"%d\", ${val%w}*10080}" ;;
    *) echo 10080 ;;
  esac
}

# ---------- Setup ----------
MINUTES=$(since_to_minutes "$SINCE")
CURRENT_PATH="$(pwd)"
TIMESTAMP="$(date '+%Y-%m-%d %H:%M:%S')"

# ---------- Active Phase ----------
ACTIVE_PHASE="(none)"
[ -f POINTER ] && ACTIVE_PHASE="$(cat POINTER | tr -d '\r\n')"

# ---------- Folder tree ----------
FOLDER_STRUCTURE=""
if ! $FAST; then
  if command -v tree >/dev/null 2>&1; then
    FOLDER_STRUCTURE="$(tree -L "$DEPTH" --dirsfirst --filelimit 12 . 2>/dev/null)"
  else
    FOLDER_STRUCTURE="(tree not found → using find)\n$(find . -maxdepth "$DEPTH" -type d | sed 's/^/  /')"
    echo "${YELLOW}⚠️ Tip: install 'tree' for richer folder visualization.${RESET}" >&2
  fi
else
  FOLDER_STRUCTURE="(fast mode: folder scan skipped)"
fi

# ---------- Recent files ----------
RECENT_FILES="$(find . -type f -mmin -"$MINUTES" 2>/dev/null \
  | grep -E '\.(tsx|ts|js|jsx|vue|php|blade\.php|json|ya?ml|css|scss|html|md)$' \
  | sort || true)"

# ---------- Git info ----------
if $USE_GIT && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  GIT_BRANCH="$(git branch --show-current 2>/dev/null || echo 'detached')"
  GIT_COMMIT="$(git log -1 --pretty=format:'%h - %s (%cr by %an)' 2>/dev/null || echo 'no commits')"
else
  GIT_BRANCH="N/A"
  GIT_COMMIT=$($USE_GIT && echo "Not a git repository" || echo "Skipped (no-git mode)")
fi

# ---------- Phase / pointer hints ----------
PHASE_POINTERS="(fast mode: skipped)"
if ! $FAST; then
  PHASE_POINTERS="$(grep -r --exclude-dir={node_modules,.git,dist,build} "POINTER=" . --include \*.{md,ts,tsx,txt} 2>/dev/null | head -n 20 || true)"
  [ -z "$PHASE_POINTERS" ] && PHASE_POINTERS="No pointers found"
fi

# ---------- Logging (Auto Path + File Name) ----------
SNAPSHOT_FILENAME="snapshot_$(date +%Y%m%d_%H%M%S).log"
SNAPSHOT_LOG_PATH="$TARGET_DIR/$SNAPSHOT_FILENAME"
if $LOG; then
  mkdir -p "$TARGET_DIR"
  echo "${BLUE}🧩 Ensured snapshot path:${RESET} ${BOLD}${TARGET_DIR}${RESET}"
fi

# ---------- Output ----------
if [[ "$MODE" == "json" ]]; then
  JSON_OUTPUT=$(cat <<EOF
{
  "timestamp": "$(escape_json "$TIMESTAMP")",
  "current_path": "$(escape_json "$CURRENT_PATH")",
  "active_phase": "$(escape_json "$ACTIVE_PHASE")",
  "folder_depth": $DEPTH,
  "since": "$(escape_json "$SINCE")",
  "minutes_window": $MINUTES,
  "git_enabled": $USE_GIT,
  "folder_structure": "$(escape_json "$FOLDER_STRUCTURE")",
  "recent_files": "$(escape_json "$RECENT_FILES")",
  "git": {
    "branch": "$(escape_json "$GIT_BRANCH")",
    "latest_commit": "$(escape_json "$GIT_COMMIT")"
  },
  "phase_pointers": "$(escape_json "$PHASE_POINTERS")"
}
EOF
)
  echo "$JSON_OUTPUT" > "$SNAPSHOT_LOG_PATH"
else
  echo
  echo "${BOLD}${CYAN}======================================${RESET}"
  echo "${BOLD}${CYAN}🧠 PROJECT CONTEXT SNAPSHOT — ${TIMESTAMP}${RESET}"
  echo "${BOLD}${CYAN}======================================${RESET}"
  echo
  echo "${BOLD}📂 Current Path:${RESET}"
  echo "  $CURRENT_PATH"
  echo "$DIVIDER"
  echo
  echo "${BOLD}🚀 Active Phase:${RESET}  ${CYAN}${ACTIVE_PHASE}${RESET}"
  echo "$DIVIDER"
  echo
  echo "${BOLD}🗂 Folder Structure (${DEPTH} levels):${RESET}"
  echo -e "$FOLDER_STRUCTURE" | sed 's/^/  /'
  echo "$DIVIDER"
  echo
  echo "${BOLD}🕒 Recently Modified Files (since: ${SINCE}):${RESET}"
  [[ -n "$RECENT_FILES" ]] && echo "$RECENT_FILES" | sed 's/^/  /' || echo "  No recent files found."
  echo "$DIVIDER"
  echo
  echo "${BOLD}🌿 Git:${RESET}"
  echo "  Branch: $GIT_BRANCH"
  echo "  Latest: $GIT_COMMIT"
  echo "$DIVIDER"
  echo
  echo "${BOLD}📍 Phase / Pointer Files:${RESET}"
  echo "$PHASE_POINTERS" | sed 's/^/  /'
  echo "$DIVIDER"
fi

# ---------- Neon HUD LOGGER ----------
if $LOG; then
  echo
  echo "${BOLD}${BLUE}⚡ HUD Neon Logger${RESET}"
  echo "${BLUE}╭──────────────────────────────────────────────╮${RESET}"
  echo "${BLUE}│ ${BOLD}File:${RESET} ${MAGENTA}${SNAPSHOT_FILENAME}${RESET}"
  echo "${BLUE}│ ${BOLD}Path:${RESET} ${VIOLET}${TARGET_DIR}${RESET}"
  echo "${BLUE}│ ${BOLD}Phase:${RESET} ${CYAN}${ACTIVE_PHASE}${RESET}"
  echo "${BLUE}│ ${BOLD}Time:${RESET} ${MAGENTA}${TIMESTAMP}${RESET}"
  echo "${BLUE}╰──────────────────────────────────────────────╯${RESET}"
  echo
  echo "${VIOLET}${BOLD}✨ Snapshot complete — HUD log generated.${RESET}"
fi
