#!/usr/bin/env bash
# validate-setup.sh - Validate environment before dogfood execution
#
# Purpose: Check that all prerequisites are met before starting the dogfood exercise.
# This catches common setup issues early and provides clear fixes.
#
# Usage: ./scripts/validate-setup.sh

set -euo pipefail

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

PASSED=0
FAILED=0

check() {
    local description="$1"
    echo -n "Checking: $description... "
}

pass() {
    echo -e "${GREEN}✓ PASS${NC}"
    PASSED=$((PASSED + 1))
}

fail() {
    local fix="$1"
    echo -e "${RED}✗ FAIL${NC}"
    echo -e "  ${YELLOW}Fix: $fix${NC}"
    FAILED=$((FAILED + 1))
}

echo -e "${YELLOW}=== Pre-Flight Validation ===${NC}\n"

# 1. Check Aphoria installed
check "Aphoria CLI installed"
if command -v aphoria > /dev/null 2>&1; then
    APHORIA_VERSION=$(aphoria --version 2>&1 | head -1 || echo "unknown")
    echo -e "${GREEN}✓ PASS${NC} ($APHORIA_VERSION)"
    PASSED=$((PASSED + 1))
else
    fail "Install Aphoria: cargo install aphoria (or build from source)"
fi

# 2. Check API running
check "StemeDB API running on :18180"
if curl -s -f http://localhost:18180/health > /dev/null 2>&1; then
    pass
else
    fail "Start StemeDB API on port 18180. Set STEMEDB_CORPUS_DB_DIR env var."
fi

# 3. Check corpus DB configured
check "Corpus database accessible"
if [[ -n "${STEMEDB_CORPUS_DB_DIR:-}" ]] && [[ -d "$STEMEDB_CORPUS_DB_DIR" ]]; then
    echo -e "${GREEN}✓ PASS${NC} ($STEMEDB_CORPUS_DB_DIR)"
    PASSED=$((PASSED + 1))
else
    fail "Set STEMEDB_CORPUS_DB_DIR environment variable to corpus DB path"
fi

# 4. Check claims are queryable
check "Corpus API returns data"
CORPUS_RESPONSE=$(curl -s 'http://localhost:18180/v1/aphoria/corpus?sources[]=vendor&limit=1' 2>/dev/null || echo '{}')
CORPUS_COUNT=$(echo "$CORPUS_RESPONSE" | jq -r '.total_matching // 0' 2>/dev/null || echo "0")

if [[ "$CORPUS_COUNT" -gt 0 ]]; then
    echo -e "${GREEN}✓ PASS${NC} ($CORPUS_COUNT items in corpus)"
    PASSED=$((PASSED + 1))
else
    fail "Corpus API returns 0 items. Verify corpus DB is populated or create test claims."
fi

# 5. Check jq installed (needed for JSON parsing)
check "jq JSON processor installed"
if command -v jq > /dev/null 2>&1; then
    pass
else
    fail "Install jq: apt-get install jq (or brew install jq on macOS)"
fi

# 6. Check Rust toolchain (if they need to build code)
check "Rust toolchain available"
if cargo --version > /dev/null 2>&1; then
    RUST_VERSION=$(cargo --version | head -1)
    echo -e "${GREEN}✓ PASS${NC} ($RUST_VERSION)"
    PASSED=$((PASSED + 1))
else
    fail "Install Rust: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
fi

# 7. Test extractor capability (can Aphoria find patterns?)
check "Aphoria extractors detect patterns"

# Create a minimal test file with a known pattern
TEMP_TEST=$(mktemp --suffix=.rs)
cat > "$TEMP_TEST" <<'EOF'
pub struct PoolConfig {
    pub max_connections: Option<usize>,
    pub connection_timeout: Duration,
}
EOF

# Run scan in current directory (dogfood root)
SCAN_OUTPUT=$(aphoria scan "$TEMP_TEST" --format json 2>/dev/null || echo '{"findings": []}')
FINDINGS_COUNT=$(echo "$SCAN_OUTPUT" | jq -r '.findings | length' 2>/dev/null || echo "0")
rm -f "$TEMP_TEST"

if [[ "$FINDINGS_COUNT" -gt 0 ]]; then
    echo -e "${GREEN}✓ PASS${NC} (detected $FINDINGS_COUNT patterns)"
    PASSED=$((PASSED + 1))
else
    fail "Extractors found 0 patterns. Ensure .aphoria/config.toml exists in project root."
fi

# Summary
echo -e "\n${YELLOW}=== Summary ===${NC}"
echo -e "Passed: ${GREEN}$PASSED${NC}"
echo -e "Failed: ${RED}$FAILED${NC}"

if [[ $FAILED -eq 0 ]]; then
    echo -e "\n${GREEN}✓ All checks passed. Ready to proceed with dogfood exercise!${NC}"
    exit 0
else
    echo -e "\n${RED}✗ Some checks failed. Fix issues above before proceeding.${NC}"
    echo -e "\n${YELLOW}Common fixes:${NC}"
    echo -e "  • API not running: Start StemeDB API with corpus DB configured"
    echo -e "  • No claims in corpus: Run some 'aphoria corpus create' commands first"
    echo -e "  • Extractors not working: Create .aphoria/config.toml with extractor config"
    exit 1
fi
