#!/bin/bash
# Integration tests for stablestack 0.3.1
# Tests: pip install, free tier, activation, paid tier
set -euo pipefail

TEST_DIR="$(cd "$(dirname "$0")" && pwd)"
WORK_DIR="$(mktemp -d)/stablestack-e2e"
VENV_DIR="$WORK_DIR/venv"
LICENSE_KEY="sk_live_2e5d5a9215c660750f822a848af1e049"
PASS=0
FAIL=0

green()  { printf "\033[32m%s\033[0m\n" "$1"; }
red()    { printf "\033[31m%s\033[0m\n" "$1"; }
header() { printf "\n\033[1;36m=== %s ===\033[0m\n" "$1"; }

assert_contains() {
    local label="$1" haystack="$2" needle="$3"
    if echo "$haystack" | grep -q "$needle"; then
        green "  PASS: $label"
        PASS=$((PASS + 1))
    else
        red "  FAIL: $label (expected '$needle')"
        FAIL=$((FAIL + 1))
    fi
}

assert_not_contains() {
    local label="$1" haystack="$2" needle="$3"
    if echo "$haystack" | grep -q "$needle"; then
        red "  FAIL: $label (unexpected '$needle')"
        FAIL=$((FAIL + 1))
    else
        green "  PASS: $label"
        PASS=$((PASS + 1))
    fi
}

# ─── Clean slate ───────────────────────────────────────────
header "Setup: clean environment"
rm -rf "$WORK_DIR"
mkdir -p "$WORK_DIR"
rm -rf ~/.stablestack/license.json ~/.stablestack/checkers/

# Copy test fixture to working directory
cp "$TEST_DIR/buggy_app.py" "$WORK_DIR/buggy_app.py"
cd "$WORK_DIR"

# ─── Test 1: pip install from PyPI ─────────────────────────
header "Test 1: pip install stablestack from PyPI"
python3 -m venv "$VENV_DIR"
source "$VENV_DIR/bin/activate"

PIP_OUT=$(pip install stablestack==0.3.1 2>&1)
assert_contains "pip install succeeds" "$PIP_OUT" "Successfully installed"
assert_contains "correct version installed" "$PIP_OUT" "stablestack-0.3.1"

# Verify the command exists
STATUS_CHECK=$(stablestack status 2>&1 || true)
assert_contains "stablestack command works" "$STATUS_CHECK" "0.3.1"

# ─── Test 2: Wheel excludes paid source ───────────────────
header "Test 2: Wheel excludes paid checker source"
WHEEL_PATH=$(pip show -f stablestack 2>&1 | grep "Location:" | awk '{print $2}')
SITE_CHECKERS="$WHEEL_PATH/stablestack/checkers"

# Free checkers should be present
assert_contains "security/ dir exists" "$(ls "$SITE_CHECKERS/")" "security"
assert_contains "session/ dir exists" "$(ls "$SITE_CHECKERS/")" "session"
assert_contains "schema/ dir exists" "$(ls "$SITE_CHECKERS/")" "schema"

# Paid checker dirs should NOT be present
assert_not_contains "determinism/ excluded" "$(ls "$SITE_CHECKERS/" 2>&1)" "determinism"
assert_not_contains "performance/ excluded" "$(ls "$SITE_CHECKERS/" 2>&1)" "performance"
assert_not_contains "quality/ excluded" "$(ls "$SITE_CHECKERS/" 2>&1)" "quality"
assert_not_contains "concurrency/ excluded" "$(ls "$SITE_CHECKERS/" 2>&1)" "concurrency"
assert_not_contains "kubernetes/ excluded" "$(ls "$SITE_CHECKERS/" 2>&1)" "kubernetes"

# ─── Test 3: Free tier check ──────────────────────────────
header "Test 3: Free tier (no license)"
FREE_OUT=$(stablestack check buggy_app.py 2>&1 || true)

assert_contains "shows free tier warning" "$FREE_OUT" "free-tier"
assert_contains "shows activate prompt" "$FREE_OUT" "stablestack activate"
assert_contains "finds hardcoded secret (SEC001)" "$FREE_OUT" "hardcoded secret"
assert_contains "finds SQL injection (SEC002)" "$FREE_OUT" "SQL"
assert_contains "finds eval (SEC003)" "$FREE_OUT" "eval"
assert_contains "finds insecure random (SEC004)" "$FREE_OUT" "random"
assert_contains "finds thread session (SESS002)" "$FREE_OUT" "thread-safe"

# ─── Test 4: License activation ───────────────────────────
header "Test 4: License activation with real API"
ACTIVATE_OUT=$(stablestack activate "$LICENSE_KEY" 2>&1 || true)

assert_contains "activation succeeds" "$ACTIVATE_OUT" "License valid"
assert_contains "shows license type" "$ACTIVATE_OUT" "enterprise"
assert_contains "shows customer name" "$ACTIVATE_OUT" "StableStack Team"
assert_contains "downloads paid checkers" "$ACTIVATE_OUT" "Unlocked"

# Verify license cache was saved
assert_contains "license.json created" "$(ls ~/.stablestack/license.json 2>&1)" "license.json"

# Verify checker bundle was extracted
assert_contains "manifest.json exists" "$(ls ~/.stablestack/checkers/manifest.json 2>&1)" "manifest.json"
SO_COUNT=$(ls ~/.stablestack/checkers/*.so 2>/dev/null | wc -l | tr -d ' ')
assert_contains "compiled .so files exist (>50)" "$([ "$SO_COUNT" -gt 50 ] && echo 'yes' || echo 'no')" "yes"

# ─── Test 5: Status command ───────────────────────────────
header "Test 5: stablestack status"
STATUS_OUT=$(stablestack status 2>&1)

assert_contains "shows version" "$STATUS_OUT" "0.3.1"
assert_contains "shows license type" "$STATUS_OUT" "enterprise"
assert_contains "shows customer" "$STATUS_OUT" "StableStack Team"
assert_contains "shows free checker count" "$STATUS_OUT" "Free checkers"
assert_contains "shows paid checker count" "$STATUS_OUT" "Paid checkers"

# ─── Test 6: Paid tier check ──────────────────────────────
header "Test 6: Paid tier check (all checkers)"
PAID_OUT=$(stablestack check buggy_app.py 2>&1 || true)

assert_not_contains "no free-tier warning" "$PAID_OUT" "free-tier"
assert_not_contains "no activate prompt" "$PAID_OUT" "Run stablestack activate"
assert_contains "still finds SEC001" "$PAID_OUT" "secret"
assert_contains "still finds SEC002" "$PAID_OUT" "SQL"
assert_contains "still finds SESS002" "$PAID_OUT" "thread"
assert_contains "finds errors" "$PAID_OUT" "Found"

# ─── Test 7: Invalid license key ──────────────────────────
header "Test 7: Invalid license key"
rm -f ~/.stablestack/license.json
BAD_OUT=$(stablestack activate "sk_live_bogus_key_12345" 2>&1 || true)

assert_contains "shows error for bad key" "$BAD_OUT" "failed"

# ─── Results ──────────────────────────────────────────────
deactivate
header "Results"
TOTAL=$((PASS + FAIL))
echo ""
if [ "$FAIL" -eq 0 ]; then
    green "ALL $TOTAL TESTS PASSED"
else
    red "$FAIL of $TOTAL TESTS FAILED"
    green "$PASS passed"
fi
echo ""

# Cleanup
rm -rf "$WORK_DIR"
rm -rf ~/.stablestack/license.json ~/.stablestack/checkers/

exit $FAIL
