#!/bin/bash
#
# Pack Version Update Test
#
# Tests that importing a newer version of a pack correctly updates attribution.
#
# Usage: ./test-pack-version-update.sh
#

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
APHORIA_BIN="$PROJECT_ROOT/target/release/aphoria"
TEST_DIR="/tmp/uat-version-update"

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

TESTS_PASSED=0
TESTS_FAILED=0

pass() { echo -e "${GREEN}✓${NC} $1"; TESTS_PASSED=$((TESTS_PASSED + 1)); }
fail() { echo -e "${RED}✗${NC} $1"; TESTS_FAILED=$((TESTS_FAILED + 1)); }
info() { echo -e "${YELLOW}→${NC} $1"; }
section() { echo ""; echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"; echo "$1"; echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"; }

# Build if needed
if [ ! -f "$APHORIA_BIN" ]; then
    info "Building Aphoria (release)..."
    (cd "$PROJECT_ROOT" && cargo build --release --package aphoria)
fi

rm -rf "$TEST_DIR"
mkdir -p "$TEST_DIR"

section "Step 1: Create Standards v1.0 Pack"

STANDARDS_DIR="$TEST_DIR/standards"
mkdir -p "$STANDARDS_DIR"
cd "$STANDARDS_DIR"

cat > Cargo.toml << 'EOF'
[package]
name = "security-standards"
version = "0.1.0"
edition = "2021"
EOF

cat > aphoria.toml << 'EOF'
[episteme]
data_dir = ".aphoria/db"
[project]
name = "security-standards"
EOF

mkdir -p src && echo "fn main() {}" > src/main.rs

info "Blessing TLS cert verification (v1.0)..."
"$APHORIA_BIN" bless "code://standard/tls/cert_verification" \
    --predicate enabled --value true \
    --reason "v1.0: Certificate verification required"

"$APHORIA_BIN" policy export --name "Standards-v1.0" --output standards-v1.0.pack
pass "Standards v1.0 pack created"

section "Step 2: Create Dev Project"

DEV_DIR="$TEST_DIR/dev-team"
mkdir -p "$DEV_DIR/config"
cd "$DEV_DIR"

cat > Cargo.toml << 'EOF'
[package]
name = "my-service"
version = "0.1.0"
edition = "2021"
EOF

cat > aphoria.toml << 'EOF'
[episteme]
data_dir = ".aphoria/db"
[project]
name = "my-service"
EOF

mkdir -p src && echo "fn main() {}" > src/main.rs

cat > config/tls.yaml << 'EOF'
tls:
  tls_verify: false
EOF

pass "Dev project created"

section "Step 3: Import v1.0 and Scan"

info "Importing Standards v1.0..."
"$APHORIA_BIN" policy import "$STANDARDS_DIR/standards-v1.0.pack"

info "Scanning with v1.0..."
SCAN_V1=$("$APHORIA_BIN" scan --persist --format json 2>&1)
echo "$SCAN_V1" > scan-v1.json

VERSION_V1=$(grep -o '"pack_name"[[:space:]]*:[[:space:]]*"[^"]*"' scan-v1.json | head -1 | sed 's/.*"\([^"]*\)"$/\1/')

if [ "$VERSION_V1" = "Standards-v1.0" ]; then
    pass "v1.0 attribution correct: $VERSION_V1"
else
    fail "Expected Standards-v1.0, got: $VERSION_V1"
fi

section "Step 4: Create Standards v2.0 Pack"

cd "$STANDARDS_DIR"
rm -rf .aphoria

info "Re-initializing for v2.0..."
"$APHORIA_BIN" bless "code://standard/tls/cert_verification" \
    --predicate enabled --value true \
    --reason "v2.0: Certificate verification MANDATORY (updated policy)"

"$APHORIA_BIN" policy export --name "Standards-v2.0" --output standards-v2.0.pack
pass "Standards v2.0 pack created"

section "Step 5: Import v2.0 and Re-Scan"

cd "$DEV_DIR"

info "Importing Standards v2.0..."
"$APHORIA_BIN" policy import "$STANDARDS_DIR/standards-v2.0.pack"

info "Scanning with v2.0..."
SCAN_V2=$("$APHORIA_BIN" scan --persist --format json 2>&1)
echo "$SCAN_V2" > scan-v2.json

VERSION_V2=$(grep -o '"pack_name"[[:space:]]*:[[:space:]]*"[^"]*"' scan-v2.json | head -1 | sed 's/.*"\([^"]*\)"$/\1/')

if [ "$VERSION_V2" = "Standards-v2.0" ]; then
    pass "v2.0 attribution correct: $VERSION_V2"
else
    fail "Expected Standards-v2.0, got: $VERSION_V2"
fi

section "Step 6: Verify v1.0 No Longer Appears"

V1_APPEARS=$(grep "Standards-v1.0" scan-v2.json 2>/dev/null | wc -l | tr -d ' ')

if [ "$V1_APPEARS" -eq 0 ]; then
    pass "v1.0 no longer appears (correctly superseded)"
else
    fail "v1.0 still appears ${V1_APPEARS:-0} time(s)"
fi

section "Step 7: Show Version Transition"

echo ""
echo "Before (v1.0):"
grep '"pack_name"' scan-v1.json | head -3 || echo "  (no pack_name found)"

echo ""
echo "After (v2.0):"
grep '"pack_name"' scan-v2.json | head -3 || echo "  (no pack_name found)"

section "Summary"

echo ""
echo "Test Results:"
echo "  Passed: $TESTS_PASSED"
echo "  Failed: $TESTS_FAILED"
echo ""
echo "Observation:"
echo "  Pack version update works correctly"
echo "  v2.0 import supersedes v1.0 (same subject key)"
echo "  Attribution updates to reflect new version"
echo ""

if [ "$TESTS_FAILED" -gt 0 ]; then
    exit 1
else
    exit 0
fi
