#!/usr/bin/env bash
set -euo pipefail

# === Configuration ===
REPO_PATH="${REPO_PATH:-/home/gemmey1020/Documents/JEMY_WORK/tech/me/me/me/me/port}"
PROMPT_REL="gemini_prompts/PORTFOLIO_OS_SYSTEM_ARCHITECTURE_MASTER_PROMPT.md"
OUTPUT_REL="PORTFOLIO_FULL_ARCHITECTURE_REPORT.md"
MODEL="${MODEL:-gemini-2.5-pro}"
DEBUG="${DEBUG:-false}"
ALL_FILES_FLAG="${ALL_FILES_FLAG:--a}"   # set to empty to disable
SANDBOX="${SANDBOX:-}"                   # e.g., --sandbox or empty
EXTRA_ARGS="${EXTRA_ARGS:-}"             # any extra flags you want to pass

# === Helpers ===
msg()  { printf "\033[1;36m[arch-report]\033[0m %s\n" "$*"; }
err()  { printf "\033[1;31m[error]\033[0m %s\n" "$*" >&2; }
die()  { err "$*"; exit 1; }
require_cmd() { command -v "$1" >/dev/null 2>&1 || die "Missing required command: $1"; }

# === Checks ===
require_cmd gemini
require_cmd date
require_cmd sed
require_cmd tail
require_cmd wc

# Quote-safe cd
if [ ! -d "$REPO_PATH" ]; then
  die "Repository path not found: $REPO_PATH"
fi
cd "$REPO_PATH"

[ -f "$PROMPT_REL" ] || die "Prompt file not found: $PROMPT_REL"

# === Info ===
msg "Repository  : $REPO_PATH"
msg "Prompt      : $PROMPT_REL"
msg "Output      : $OUTPUT_REL"
msg "Model       : $MODEL"
msg "Debug       : $DEBUG"
msg "All Files   : $ALL_FILES_FLAG"
[ -n "$SANDBOX" ] && msg "Sandbox     : enabled"

# === Prepare temp prompt (replace {today} token) ===
TMP_PROMPT="$(mktemp)"
trap 'rm -f "$TMP_PROMPT"' EXIT
sed "s/{{today}}/2025-10-10/g" "$PROMPT_REL" > "$TMP_PROMPT"

# === Build command ===
CMD=(gemini -m "$MODEL")
# include all files in context if requested
[ -n "$ALL_FILES_FLAG" ] && CMD+=("$ALL_FILES_FLAG")
# debug flag
[ "$DEBUG" = "true" ] && CMD+=(-d)
# sandbox (optional)
[ -n "$SANDBOX" ] && CMD+=("$SANDBOX")
# extra args passthrough
[ -n "$EXTRA_ARGS" ] && CMD+=($EXTRA_ARGS)

msg "Running: ${CMD[*]}  < $PROMPT_REL  > $OUTPUT_REL"

# === Execute ===
# Pipe prompt via stdin into gemini, save output to report
cat "$TMP_PROMPT" | "${CMD[@]}" > "$OUTPUT_REL"

# === Post checks ===
if ! grep -q "✅ Full Deep Analysis Complete — Report saved as PORTFOLIO_FULL_ARCHITECTURE_REPORT.md" "$OUTPUT_REL"; then
  err "Success marker not found in output. The report may be incomplete."
else
  msg "Success marker found."
fi

# === Summary ===
msg "Report generated at: $REPO_PATH/$OUTPUT_REL"
msg "Size: $(wc -c < "$OUTPUT_REL") bytes"
msg "Preview (last 10 lines):"
tail -n 10 "$OUTPUT_REL" || true

# === Git helper (optional): set GIT_COMMIT=true to auto-commit
if [ "${GIT_COMMIT:-false}" = "true" ]; then
  require_cmd git
  git add "$PROMPT_REL" "$OUTPUT_REL" || true
  git commit -m "docs(ai): generate architecture report with 2025-10-10 using $MODEL" || true
  msg "Git commit attempted (see above)."
fi

msg "Done."
