#!/usr/bin/env bash
# CultGuard Agents - Quick Start Workflow
# 
# This script demonstrates a complete monitoring workflow:
# 1. Start Facebook monitoring
# 2. Run content analysis
# 3. Generate initial report
# 4. Start alert system
#
# Usage: ./quick-start.sh <investigation_id> <facebook_page_url>

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Parse arguments
INVESTIGATION_ID="${1:-demo-2026}"
FACEBOOK_URL="${2:-}"

if [ -z "$FACEBOOK_URL" ]; then
    echo -e "${RED}Error: Facebook page URL is required${NC}"
    echo "Usage: $0 <investigation_id> <facebook_url>"
    echo "Example: $0 lebanon-liberates-2026 'https://facebook.com/page-url'"
    exit 1
fi

echo -e "${BLUE}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║       CultGuard Autonomous Monitoring Workflow        ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════════════╝${NC}"
echo
echo -e "${GREEN}Investigation:${NC} $INVESTIGATION_ID"
echo -e "${GREEN}Facebook URL:${NC} $FACEBOOK_URL"
echo

# Check if devenv is running
echo -e "${YELLOW}[1/6] Checking environment...${NC}"
if ! pgrep -f "devenv" > /dev/null; then
    echo -e "${RED}⚠️  devenv is not running. Please start it first:${NC}"
    echo "   devenv up"
    exit 1
fi
echo -e "${GREEN}✓ Environment OK${NC}"
echo

# Verify database connection
echo -e "${YELLOW}[2/6] Checking database connection...${NC}"
if ! command -v db-stats &> /dev/null; then
    echo -e "${RED}⚠️  Please enter devenv shell first:${NC}"
    echo "   devenv shell"
    exit 1
fi

if ! db-stats > /dev/null 2>&1; then
    echo -e "${RED}✗ Database connection failed${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Database connected${NC}"
echo

# Initial scrape
echo -e "${YELLOW}[3/6] Performing initial Facebook scrape...${NC}"
echo "   This may take a few minutes..."
fb-scrape "$FACEBOOK_URL" --depth 25 --save --investigation "$INVESTIGATION_ID" --comments
echo -e "${GREEN}✓ Initial scrape complete${NC}"
echo

# Start monitoring agent (background)
echo -e "${YELLOW}[4/6] Starting autonomous monitoring agent...${NC}"
echo "   Monitoring interval: 30 minutes"
echo "   Auto-ingest: enabled"
echo "   Press Ctrl+C to stop monitoring"
echo

# Create a log directory
mkdir -p logs

# Start monitor in background
agent-monitor \
    --investigation "$INVESTIGATION_ID" \
    --page "$FACEBOOK_URL" \
    --interval 30 \
    --auto-ingest true \
    --alert-threshold 10 \
    > "logs/monitor-${INVESTIGATION_ID}.log" 2>&1 &

MONITOR_PID=$!
echo -e "${GREEN}✓ Monitor started (PID: $MONITOR_PID)${NC}"
echo "   Log file: logs/monitor-${INVESTIGATION_ID}.log"
echo

# Wait for initial monitoring cycle
echo -e "${YELLOW}[5/6] Waiting for initial monitoring cycle...${NC}"
sleep 10

# Check if monitor is still running
if ! kill -0 $MONITOR_PID 2>/dev/null; then
    echo -e "${RED}✗ Monitor crashed. Check logs:${NC}"
    tail -50 "logs/monitor-${INVESTIGATION_ID}.log"
    exit 1
fi
echo -e "${GREEN}✓ Monitor running${NC}"
echo

# Generate initial report
echo -e "${YELLOW}[6/6] Generating initial monitoring report...${NC}"
echo

# Use pi to generate report (non-interactive)
tmpdir="${TMPDIR:-/tmp}"; mkdir -p "$tmpdir/cultguard-report"
prompt_file="$tmpdir/cultguard-report/prompt.txt"
cat > "$prompt_file" << EOF
Generate a comprehensive monitoring report for investigation "${INVESTIGATION_ID}".
Include:
1. Entity summary (pages, profiles, etc.)
2. Content timeline (last 24 hours)
3. Top content by engagement
4. Any high-risk content detected
5. Network relationships if available

Format as a structured report with sections and key findings.
EOF

pi -p @"$prompt_file" \
    "Generate monitoring report for investigation ${INVESTIGATION_ID}. Focus on entity summary, content timeline, top content by engagement, and high-risk content." \
    > "reports/initial-report-${INVESTIGATION_ID}-$(date +%Y%m%d-%H%M%S).md" 2>&1 || {
    echo -e "${YELLOW}⚠️  pi command failed. You can generate the report manually with:${NC}"
    echo "   pi"
    echo "   /generate_report --investigation ${INVESTIGATION_ID} --time_range_hours 24 --format detailed"
}

echo -e "${GREEN}✓ Report generated${NC}"
echo

# Summary
echo -e "${BLUE}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║                  Workflow Complete                     ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════════════╝${NC}"
echo
echo -e "${GREEN}Summary:${NC}"
echo "  • Investigation: ${INVESTIGATION_ID}"
echo "  • Facebook page: ${FACEBOOK_URL}"
echo "  • Monitor PID: ${MONITOR_PID}"
echo "  • Monitor log: logs/monitor-${INVESTIGATION_ID}.log"
echo
echo -e "${YELLOW}Next Steps:${NC}"
echo
echo "1. View monitoring status:"
echo "   pi"
echo "   /monitoring-status"
echo
echo "2. Check for new content:"
echo "   pi"
echo "   /check_new_content --investigation ${INVESTIGATION_ID} --since_minutes 60"
echo
echo "3. Analyze content for risks:"
echo "   agent-analyzer -- --investigation ${INVESTIGATION_ID} --batch-size 50 --llm"
echo
echo "4. Start alert system (configure email first):"
echo "   agent-alert -- --investigation ${INVESTIGATION_ID} --channel email --email your@email.com"
echo
echo "5. Start evidence collector:"
echo "   agent-collector -- --investigation ${INVESTIGATION_ID} --auto --interval 10"
echo
echo "6. Stop monitoring agent:"
echo "   kill ${MONITOR_PID}"
echo
echo "7. View logs:"
echo "   tail -f logs/monitor-${INVESTIGATION_ID}.log"
echo
echo -e "${GREEN}All systems operational!${NC}"
