#!/usr/bin/env bash
# Consumer Health Demo Script
# Demonstrates StemeDB + stemedb-ontology for the Consumer Health use case
#
# Prerequisites:
#   - StemeDB API running: cargo run -p stemedb-api
#   - steme-pharma built: cargo build -p stemedb-ontology
#
# Usage:
#   ./scripts/demo-consumer-health.sh

set -e

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

# Configuration
STEMEDB_URL="${STEMEDB_URL:-http://localhost:18180}"
PHARMA_CLI="./target/release/steme-pharma"
PAUSE_SECONDS=2

# Helper functions
print_header() {
    echo -e "\n${BOLD}${BLUE}════════════════════════════════════════════════════════════════${NC}"
    echo -e "${BOLD}${BLUE}  $1${NC}"
    echo -e "${BOLD}${BLUE}════════════════════════════════════════════════════════════════${NC}\n"
}

print_step() {
    echo -e "${CYAN}▶ $1${NC}"
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

wait_for_user() {
    if [ -t 0 ]; then
        echo -e "\n${YELLOW}Press Enter to continue...${NC}"
        read -r
    else
        sleep $PAUSE_SECONDS
    fi
}

# Check prerequisites
print_header "Consumer Health Demo - Prerequisites Check"

# Check if steme-pharma exists
if [ ! -f "$PHARMA_CLI" ]; then
    print_warning "steme-pharma not found at $PHARMA_CLI"
    print_step "Building steme-pharma..."
    cargo build --release -p stemedb-ontology
fi

# Check if StemeDB is running
print_step "Checking StemeDB connection..."
if curl -s "${STEMEDB_URL}/v1/health" > /dev/null 2>&1; then
    print_success "StemeDB is running at $STEMEDB_URL"
else
    print_error "StemeDB not reachable at $STEMEDB_URL"
    echo -e "\nStart StemeDB with:"
    echo -e "  ${CYAN}cargo run -p stemedb-api${NC}"
    exit 1
fi

# ============================================================================
# STEP 1: Ingest FDA Data + Mock Conflicts
# ============================================================================
print_header "Step 1: Ingest FDA Data + Mock Conflicts"

print_step "Ingesting FDA label data for Semaglutide and Tirzepatide..."
print_step "Adding mock conflicts (simulating social media contradictions)..."
echo ""

$PHARMA_CLI --stemedb-url "$STEMEDB_URL" ingest "semaglutide,tirzepatide" --with-conflicts

print_success "Data ingested with mock conflicts"
wait_for_user

# ============================================================================
# STEP 2: Conflict Detection (Skeptic Lens)
# ============================================================================
print_header "Step 2: Conflict Detection (Skeptic Lens)"

echo -e "${BOLD}Question:${NC} What do different sources say about Semaglutide's nausea rate?"
echo -e "${BOLD}Lens:${NC} Skeptic (shows all claims, highlights disagreements)\n"

print_step "Querying nausea_rate with Skeptic lens..."
echo ""

$PHARMA_CLI --stemedb-url "$STEMEDB_URL" query "Semaglutide" "nausea_rate" --mode skeptic

echo -e "\n${YELLOW}Note:${NC} The conflict score indicates disagreement between sources."
echo -e "FDA (Regulatory tier) reports clinical trial data."
echo -e "Reddit (Anecdotal tier) reports user experiences."
wait_for_user

# ============================================================================
# STEP 3: Source Hierarchy (Layered Consensus)
# ============================================================================
print_header "Step 3: Source Hierarchy (Layered Consensus)"

echo -e "${BOLD}Question:${NC} What's the consensus on HbA1c reduction, broken down by source tier?"
echo -e "${BOLD}Lens:${NC} LayeredConsensus (shows per-tier agreement)\n"

print_step "Querying hba1c_reduction_percent with Layered Consensus..."
echo ""

$PHARMA_CLI --stemedb-url "$STEMEDB_URL" query "Semaglutide:Type2Diabetes" "hba1c_reduction_percent" --mode layered

echo -e "\n${YELLOW}Note:${NC} Each tier shows its own consensus."
echo -e "Higher tiers (Regulatory, Clinical) have more weight in final resolution."
wait_for_user

# ============================================================================
# STEP 4: Drug Comparison
# ============================================================================
print_header "Step 4: Drug Comparison"

echo -e "${BOLD}Question:${NC} How do Semaglutide and Tirzepatide compare on weight loss?"
echo -e "${BOLD}Method:${NC} Side-by-side query of both subjects\n"

print_step "Comparing weight_loss_percent..."
echo ""

$PHARMA_CLI --stemedb-url "$STEMEDB_URL" compare \
    "Semaglutide:Type2Diabetes" \
    "Tirzepatide:Type2Diabetes" \
    --predicate "weight_loss_percent"

echo -e "\n${YELLOW}Note:${NC} Both drugs' claims are shown with conflict scores."
echo -e "A consumer can see both FDA data and community reports."
wait_for_user

# ============================================================================
# STEP 5: Explore Available Data
# ============================================================================
print_header "Step 5: Explore Available Data"

echo -e "${BOLD}Question:${NC} What predicates are available for Semaglutide?"
echo -e "${BOLD}Method:${NC} List all predicates with assertions for this subject\n"

print_step "Exploring Semaglutide predicates..."
echo ""

$PHARMA_CLI --stemedb-url "$STEMEDB_URL" explore "Semaglutide:Type2Diabetes"

echo ""

print_step "Exploring Semaglutide safety predicates..."
echo ""

$PHARMA_CLI --stemedb-url "$STEMEDB_URL" explore "Semaglutide"

echo -e "\n${YELLOW}Note:${NC} Efficacy predicates use Drug:Indication subjects."
echo -e "Safety predicates use Drug-only subjects (apply across indications)."
wait_for_user

# ============================================================================
# STEP 6: JSON Output (for Integration)
# ============================================================================
print_header "Step 6: JSON Output (for Integration)"

echo -e "${BOLD}Use Case:${NC} Programmatic access for AI agents or web apps"
echo -e "${BOLD}Format:${NC} JSON output for parsing\n"

print_step "Getting JSON response..."
echo ""

$PHARMA_CLI --stemedb-url "$STEMEDB_URL" --format json query "Semaglutide" "nausea_rate" | head -50

echo -e "\n... (truncated for demo)"
wait_for_user

# ============================================================================
# Summary
# ============================================================================
print_header "Demo Summary"

echo -e "${GREEN}${BOLD}What We Demonstrated:${NC}\n"

echo -e "  1. ${CYAN}Data Ingestion${NC}"
echo -e "     - FDA label extraction (Regulatory tier)"
echo -e "     - Mock social media conflicts (Anecdotal tier)"
echo ""

echo -e "  2. ${CYAN}Conflict Detection${NC}"
echo -e "     - Skeptic lens shows ALL claims"
echo -e "     - Conflict score quantifies disagreement"
echo ""

echo -e "  3. ${CYAN}Source Hierarchy${NC}"
echo -e "     - LayeredConsensus groups by authority tier"
echo -e "     - FDA data weighted higher than Reddit"
echo ""

echo -e "  4. ${CYAN}Drug Comparison${NC}"
echo -e "     - Side-by-side view of multiple subjects"
echo -e "     - Each drug's claims with provenance"
echo ""

echo -e "  5. ${CYAN}Data Exploration${NC}"
echo -e "     - Discover available predicates"
echo -e "     - Different subject patterns for efficacy vs safety"
echo ""

echo -e "  6. ${CYAN}API Integration${NC}"
echo -e "     - JSON output for programmatic access"
echo -e "     - Ready for AI agents and web apps"
echo ""

echo -e "${BOLD}Consumer Health Value Proposition:${NC}"
echo -e "  - ${GREEN}See all perspectives${NC}, not just the loudest"
echo -e "  - ${GREEN}Understand source authority${NC} (FDA vs. Reddit)"
echo -e "  - ${GREEN}Make informed decisions${NC} with conflict awareness"
echo ""

echo -e "${BOLD}Next Steps:${NC}"
echo -e "  - Run Consumer Health UAT: ${CYAN}cargo test -p stemedb-ontology --test consumer_health_uat${NC}"
echo -e "  - Read the guide: ${CYAN}docs/app-concepts/consumer-health.md${NC}"
echo -e "  - Try the Go SDK: ${CYAN}sdk/go/steme/${NC}"
echo ""

print_success "Demo complete!"
