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

VERBOSE=0
GRAPH_PATH="${GRAPH_PATH:-.omp/graph/baria.lbug}"

while [[ $# -gt 0 ]]; do
  case $1 in
    --skeleton)
      SKELETON_PATH="$2"
      shift 2
      ;;
    --graph-path)
      GRAPH_PATH="$2"
      shift 2
      ;;
    --verbose)
      VERBOSE=1
      shift
      ;;
    *)
      echo "Unknown option: $1"
      echo "Usage: graph-context ingest-skeleton --skeleton PATH [--graph-path PATH] [--verbose]"
      exit 1
      ;;
  esac
done

if [ -z "${SKELETON_PATH:-}" ]; then
  echo "Error: --skeleton is required"
  echo "Usage: graph-context ingest-skeleton --skeleton PATH [--graph-path PATH] [--verbose]"
  exit 1
fi

if [ ! -f "${SKELETON_PATH}" ]; then
  echo "Error: Skeleton file not found: ${SKELETON_PATH}"
  exit 1
fi

if [ ! -f "${GRAPH_PATH}" ]; then
  echo "Error: Graph file not found: ${GRAPH_PATH}"
  echo "Run 'graph-context init-graph' first to create the graph."
  exit 1
fi

if [ "$VERBOSE" -eq 1 ]; then
  echo "Parsing skeleton.md: ${SKELETON_PATH}"
fi

# Generate Cypher statements using Python script
python3 /Users/bparlan/devcode/aef/agent/skills/graph-context/bin/ingest-skeleton.py "${SKELETON_PATH}" 2>&1 | grep -v "^DEBUG:" > /tmp/ingest_cypher.txt

if [ "$VERBOSE" -eq 1 ]; then
  echo "Executing Cypher statements via lbug..."
fi

# Execute Cypher statements
lbug "${GRAPH_PATH}" < /tmp/ingest_cypher.txt 2>/dev/null

if [ "$VERBOSE" -eq 1 ]; then
  echo "Verifying graph state..."
fi

# Count created nodes and edges
file_count=$(echo "MATCH (f:File) RETURN count(f)" | lbug "${GRAPH_PATH}")
symbol_count=$(echo "MATCH (s:Symbol) RETURN count(s)" | lbug "${GRAPH_PATH}")
import_count=$(echo "MATCH ()-[i:IMPORTS]->() RETURN count(i)" | lbug "${GRAPH_PATH}")

echo "✅ Skeleton ingested successfully"
echo "   Files: ${file_count}"
echo "   Symbols: ${symbol_count}"
echo "   IMPORTS edges: ${import_count}"
