#!/bin/bash
set -e  # Exit on any error

# ============================================================================
# Story Verification Script
# ============================================================================
# Purpose: Deterministic verification of XLR8 story completion
# Usage: ./scripts/verify-story.sh GG-XXX
# Exit codes: 0 = PASS, 1 = FAIL
# ============================================================================

STORY_ID="$1"
DOMAIN="$2"  # Optional: Ordering, Gala, Notifications, Venue

if [ -z "$STORY_ID" ]; then
    echo "❌ Usage: ./scripts/verify-story.sh GG-XXX [domain]"
    exit 1
fi

echo "========================================================================"
echo "Verifying Story: $STORY_ID"
echo "========================================================================"
echo ""

# Determine domain from story ID if not provided
if [ -z "$DOMAIN" ]; then
    case "$STORY_ID" in
        GG-170|GG-171|GG-172) DOMAIN="Venue" ;;
        GG-173|GG-174|GG-175|GG-176|GG-177|GG-178|GG-179|GG-180) DOMAIN="Ordering" ;;
        GG-181|GG-182|GG-183|GG-184|GG-185|GG-186|GG-187|GG-188|GG-189) DOMAIN="Gala" ;;
        GG-190|GG-191|GG-192|GG-193|GG-194|GG-195|GG-196|GG-197|GG-198|GG-199|GG-200|GG-201) DOMAIN="Notifications" ;;
        *)
            echo "❌ Cannot determine domain for story $STORY_ID"
            exit 1
            ;;
    esac
fi

echo "Domain: $DOMAIN"
echo ""

DOMAIN_PATH="app/Domains/$DOMAIN"
FAILED=0

# ============================================================================
# 1. SYNTAX CHECK (fast, catches obvious errors)
# ============================================================================
echo "[1/5] Syntax Check..."

if ! find "$DOMAIN_PATH" -name "*.php" -exec php -l {} \; > /tmp/syntax-check.log 2>&1; then
    echo "❌ FAIL: PHP syntax errors detected"
    grep "Parse error" /tmp/syntax-check.log | head -5
    FAILED=1
else
    echo "✓ PASS: No syntax errors"
fi
echo ""

# ============================================================================
# 2. LARASTAN (type safety)
# ============================================================================
echo "[2/5] Larastan Type Safety..."

# Run Larastan on domain
if ./vendor/bin/phpstan analyse "$DOMAIN_PATH" --level=6 --no-progress --error-format=raw > /tmp/larastan-current.txt 2>&1; then
    ERROR_COUNT=0
    echo "✓ PASS: 0 Larastan errors"
else
    ERROR_COUNT=$(grep -c ":" /tmp/larastan-current.txt || echo "0")
    echo "⚠ INFO: $ERROR_COUNT Larastan errors (baseline may have pre-existing errors)"

    # Check if errors increased (bad) vs stayed same/decreased (ok)
    if [ -f /tmp/larastan-baseline.txt ]; then
        BASELINE_COUNT=$(grep -c ":" /tmp/larastan-baseline.txt || echo "0")
        if [ "$ERROR_COUNT" -gt "$BASELINE_COUNT" ]; then
            echo "❌ FAIL: Larastan errors INCREASED ($BASELINE_COUNT → $ERROR_COUNT)"
            diff /tmp/larastan-baseline.txt /tmp/larastan-current.txt | head -20
            FAILED=1
        else
            echo "✓ PASS: Larastan errors did not increase ($BASELINE_COUNT → $ERROR_COUNT)"
        fi
    fi
fi

# Save as new baseline
cp /tmp/larastan-current.txt /tmp/larastan-baseline.txt
echo ""

# ============================================================================
# 3. PINT (code style)
# ============================================================================
echo "[3/5] Code Style (Pint)..."

if ./vendor/bin/pint --test "$DOMAIN_PATH" > /tmp/pint-check.log 2>&1; then
    echo "✓ PASS: No Pint violations"
else
    VIOLATION_COUNT=$(grep -c "⨯" /tmp/pint-check.log || echo "0")

    if [ "$VIOLATION_COUNT" -gt 0 ]; then
        echo "⚠ INFO: $VIOLATION_COUNT Pint violations (may be pre-existing)"

        # Check if violations increased
        if [ -f /tmp/pint-baseline.txt ]; then
            BASELINE_COUNT=$(grep -c "⨯" /tmp/pint-baseline.txt || echo "0")
            if [ "$VIOLATION_COUNT" -gt "$BASELINE_COUNT" ]; then
                echo "❌ FAIL: Pint violations INCREASED ($BASELINE_COUNT → $VIOLATION_COUNT)"
                FAILED=1
            else
                echo "✓ PASS: Pint violations did not increase"
            fi
        fi
    fi
fi

cp /tmp/pint-check.log /tmp/pint-baseline.txt
echo ""

# ============================================================================
# 4. TESTS (functionality)
# ============================================================================
echo "[4/5] Domain Tests..."

if vendor/bin/phpunit --filter="$DOMAIN" --testdox --no-coverage > /tmp/test-results.log 2>&1; then
    PASSED=$(grep -c "✔" /tmp/test-results.log || echo "0")
    echo "✓ PASS: All tests passed ($PASSED tests)"
else
    FAILED_TESTS=$(grep -c "✘" /tmp/test-results.log || echo "0")
    echo "❌ FAIL: $FAILED_TESTS tests failed"
    grep "✘" /tmp/test-results.log | head -10
    FAILED=1
fi
echo ""

# ============================================================================
# 5. STORY-SPECIFIC CHECKS
# ============================================================================
echo "[5/5] Story-Specific Checks..."

case "$STORY_ID" in
    # VENUE STORIES
    GG-170)
        echo "Checking: Larastan errors in Venue = 0"
        if [ "$ERROR_COUNT" -eq 0 ]; then
            echo "✓ PASS: 0 Larastan errors"
        else
            echo "❌ FAIL: Expected 0 errors, got $ERROR_COUNT"
            FAILED=1
        fi
        ;;

    GG-171)
        echo "Checking: Pint violations in Venue = 0"
        if [ "$VIOLATION_COUNT" -eq 0 ]; then
            echo "✓ PASS: 0 Pint violations"
        else
            echo "❌ FAIL: Expected 0 violations, got $VIOLATION_COUNT"
            FAILED=1
        fi
        ;;

    GG-172)
        echo "Checking: VOs, enums, events exist"
        if [ -f "app/Domains/Venue/ValueObjects/VenueCapacityVO.php" ]; then
            echo "✓ PASS: VenueCapacityVO created"
        else
            echo "❌ FAIL: VenueCapacityVO not found"
            FAILED=1
        fi
        ;;

    # ORDERING STORIES
    GG-173)
        echo "Checking: Magic strings eliminated in Ordering services"
        MAGIC_COUNT=$(grep -r "status.*=.*['\"]pending['\"]" app/Domains/Ordering/Services --include="*.php" | grep -v "//" | wc -l | xargs)
        if [ "$MAGIC_COUNT" -eq 0 ]; then
            echo "✓ PASS: 0 magic 'pending' strings"
        else
            echo "❌ FAIL: Found $MAGIC_COUNT magic strings"
            grep -rn "status.*=.*['\"]pending['\"]" app/Domains/Ordering/Services --include="*.php" | grep -v "//" | head -5
            FAILED=1
        fi

        echo "Checking: Enums exist"
        for enum in OrderStatus PaymentStatus PaymentGateway; do
            if [ -f "app/Enums/$enum.php" ]; then
                echo "✓ PASS: $enum enum exists"
            else
                echo "❌ FAIL: $enum enum not found"
                FAILED=1
            fi
        done
        ;;

    GG-174)
        echo "Checking: DTOs created"
        for dto in OrderDTO PaymentDTO RefundDTO; do
            if [ -f "app/Domains/Ordering/DTOs/$dto.php" ]; then
                echo "✓ PASS: $dto created"
            else
                echo "❌ FAIL: $dto not found"
                FAILED=1
            fi
        done
        ;;

    GG-175)
        echo "Checking: Domain exceptions created"
        if [ -f "app/Domains/Ordering/Exceptions/OrderingException.php" ]; then
            echo "✓ PASS: Base OrderingException created"
        else
            echo "❌ FAIL: OrderingException not found"
            FAILED=1
        fi

        echo "Checking: No generic Exception throws in services"
        GENERIC_THROWS=$(grep -r "throw new \\\\Exception" app/Domains/Ordering/Services --include="*.php" | wc -l | xargs)
        if [ "$GENERIC_THROWS" -eq 0 ]; then
            echo "✓ PASS: No generic Exception throws"
        else
            echo "❌ FAIL: Found $GENERIC_THROWS generic Exception throws"
            FAILED=1
        fi
        ;;

    GG-179)
        echo "Checking: RevolutPaymentGateway split"
        GATEWAY_LINES=$(wc -l < app/Domains/Ordering/Services/Payment/RevolutPaymentGateway.php | xargs)
        if [ "$GATEWAY_LINES" -lt 500 ]; then
            echo "✓ PASS: RevolutPaymentGateway has $GATEWAY_LINES lines (<500)"
        else
            echo "❌ FAIL: RevolutPaymentGateway still has $GATEWAY_LINES lines (>500)"
            FAILED=1
        fi

        echo "Checking: Extracted services exist"
        for service in RevolutWebhookHandler RevolutRefundService; do
            if [ -f "app/Domains/Ordering/Services/Payment/$service.php" ]; then
                echo "✓ PASS: $service created"
            else
                echo "❌ FAIL: $service not found"
                FAILED=1
            fi
        done
        ;;

    # GALA STORIES
    GG-181)
        echo "Checking: GalaForkService split"
        FORK_LINES=$(wc -l < app/Domains/Gala/Services/GalaForkService.php | xargs)
        if [ "$FORK_LINES" -lt 300 ]; then
            echo "✓ PASS: GalaForkService has $FORK_LINES lines (<300)"
        else
            echo "❌ FAIL: GalaForkService still has $FORK_LINES lines (>300)"
            FAILED=1
        fi
        ;;

    # NOTIFICATIONS STORIES
    GG-190)
        echo "Checking: Magic strings eliminated in Notifications"
        MAGIC_COUNT=$(grep -r "type.*=.*['\"]email['\"]" app/Domains/Notifications/Services --include="*.php" | grep -v "//" | wc -l | xargs)
        if [ "$MAGIC_COUNT" -eq 0 ]; then
            echo "✓ PASS: 0 magic notification type strings"
        else
            echo "❌ FAIL: Found $MAGIC_COUNT magic strings"
            FAILED=1
        fi
        ;;

    GG-193)
        echo "Checking: EmailNotificationService extracted"
        if [ -f "app/Domains/Notifications/Services/EmailNotificationService.php" ]; then
            EMAIL_LINES=$(wc -l < app/Domains/Notifications/Services/EmailNotificationService.php | xargs)
            echo "✓ PASS: EmailNotificationService created ($EMAIL_LINES lines)"
        else
            echo "❌ FAIL: EmailNotificationService not found"
            FAILED=1
        fi

        echo "Checking: NotificationService reduced"
        if [ -f "app/Domains/Notifications/Services/NotificationService.php" ]; then
            NOTIF_LINES=$(wc -l < app/Domains/Notifications/Services/NotificationService.php | xargs)
            if [ "$NOTIF_LINES" -lt 1400 ]; then
                echo "✓ PASS: NotificationService reduced to $NOTIF_LINES lines"
            else
                echo "❌ FAIL: NotificationService still $NOTIF_LINES lines (should be <1400)"
                FAILED=1
            fi
        fi
        ;;

    *)
        echo "⚠ No specific checks defined for $STORY_ID"
        echo "Using generic checks only"
        ;;
esac
echo ""

# ============================================================================
# FINAL VERDICT
# ============================================================================
echo "========================================================================"
if [ $FAILED -eq 0 ]; then
    echo "✅ VERIFICATION PASSED: Story $STORY_ID"
    echo "========================================================================"
    exit 0
else
    echo "❌ VERIFICATION FAILED: Story $STORY_ID"
    echo "========================================================================"
    echo ""
    echo "Fix the issues above and run verification again:"
    echo "  ./scripts/verify-story.sh $STORY_ID"
    echo ""
    exit 1
fi
