#!/bin/bash
# Compliance Verification Script
# Run this before launching to verify all compliance controls are in place

set -e

echo "========================================"
echo "RankWiz AI — Compliance Verification"
echo "========================================"
echo ""

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

SCORE=0
TOTAL=0

check() {
    TOTAL=$((TOTAL + 1))
    local name=$1
    local cmd=$2

    echo -n "[$TOTAL] $name... "

    if eval "$cmd" > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC}"
        SCORE=$((SCORE + 1))
    else
        echo -e "${RED}✗${NC}"
    fi
}

# ============ ENCRYPTION ============
echo ""
echo -e "${YELLOW}=== ENCRYPTION ===${NC}"

check "AES-256-CBC cipher configured" \
    "grep -q 'APP_CIPHER.*aes-256-cbc' .env"

check "Session encryption enabled" \
    "grep -q \"'encrypt' => env('SESSION_ENCRYPT', true)\" config/session.php"

check "UserAiKey.api_key encrypted" \
    "grep -q \"'api_key' => 'encrypted'\" app/Models/UserAiKey.php"

check "GscConnection tokens encrypted" \
    "grep -q \"'access_token' => 'encrypted'\" app/Models/GscConnection.php && \
     grep -q \"'refresh_token' => 'encrypted'\" app/Models/GscConnection.php"

check "WpConnection secrets encrypted" \
    "grep -q \"'shared_secret' => 'encrypted'\" app/Models/WpConnection.php"

# ============ DATA DELETION ============
echo ""
echo -e "${YELLOW}=== DATA DELETION ===${NC}"

check "UserDeletionService exists" \
    "[ -f app/Services/UserDeletionService.php ]"

check "PurgeSoftDeletedDataJob exists" \
    "[ -f app/Jobs/PurgeSoftDeletedDataJob.php ]"

check "ProfileController.destroy() exists" \
    "grep -q 'public function destroy' app/Http/Controllers/ProfileController.php"

check "Soft-delete purge scheduled" \
    "grep -q 'PurgeSoftDeletedDataJob' routes/console.php"

# ============ DSAR EXPORT ============
echo ""
echo -e "${YELLOW}=== DSAR EXPORT ===${NC}"

check "DsarExportService exists" \
    "[ -f app/Services/DsarExportService.php ]"

check "ProfileController.export() exists" \
    "grep -q 'public function export' app/Http/Controllers/ProfileController.php"

check "Profile export route registered" \
    "grep -q \"'profile.export'\" routes/dashboard.php"

check "DSAR export includes audit logs" \
    "grep -q 'exportAuditLogs' app/Services/DsarExportService.php"

check "DSAR export includes billing data" \
    "grep -q 'exportBillingData' app/Services/DsarExportService.php"

# ============ AUDIT LOGGING ============
echo ""
echo -e "${YELLOW}=== AUDIT LOGGING ===${NC}"

check "AuditService exists" \
    "[ -f app/Services/AuditService.php ]"

check "AuditService redacts PII" \
    "grep -q 'sanitizeContext' app/Services/AuditService.php"

check "AuditLog model has action column" \
    "grep -q \"'action'\" app/Models/AuditLog.php"

check "Audit logs migration exists" \
    "[ -f database/migrations/*create_audit_logs_table.php ] || \
     [ -f database/migrations/*improve_audit_logs_table.php ]"

# ============ BREACH NOTIFICATION ============
echo ""
echo -e "${YELLOW}=== BREACH NOTIFICATION ===${NC}"

check "BreachNotificationService exists" \
    "[ -f app/Services/BreachNotificationService.php ]"

check "BreachIncident model exists" \
    "[ -f app/Models/BreachIncident.php ]"

check "DataBreachNotification mailable exists" \
    "[ -f app/Notifications/DataBreachNotification.php ]"

check "Breach config has GDPR hours" \
    "grep -q 'gdpr_notification_hours' config/breach.php"

# ============ COOKIE CONSENT ============
echo ""
echo -e "${YELLOW}=== COOKIE CONSENT ===${NC}"

check "CookieConsent model exists" \
    "[ -f app/Models/CookieConsent.php ]"

check "CookieConsentController exists" \
    "[ -f app/Http/Controllers/CookieConsentController.php ]"

check "IP hashing in CookieConsentController" \
    "grep -q 'hashIp\|hash_hmac' app/Http/Controllers/CookieConsentController.php"

check "Cookie consent routes registered" \
    "grep -q 'cookie-consent' routes/marketing.php"

# ============ DATA RETENTION ============
echo ""
echo -e "${YELLOW}=== DATA RETENTION ===${NC}"

check "Retention days configured in limits" \
    "grep -q 'retention_days' config/limits.php"

check "PruneGscMetricsJob exists" \
    "[ -f app/Jobs/PruneGscMetricsJob.php ]"

check "Prune jobs scheduled in console" \
    "grep -q 'prune-content-snapshots\|prune-roi-snapshots' routes/console.php"

check "Soft delete retention configured" \
    "grep -q 'soft_delete_purge_days' config/limits.php"

# ============ LEGAL DOCUMENTS ============
echo ""
echo -e "${YELLOW}=== LEGAL DOCUMENTS ===${NC}"

check "Privacy Policy exists" \
    "[ -f legal/privacy-policy.md ]"

check "Terms of Service exists" \
    "[ -f legal/terms-of-service.md ]"

check "Data Processing Agreement exists" \
    "[ -f legal/data-processing-agreement.md ]"

check "Acceptable Use Policy exists" \
    "[ -f legal/acceptable-use-policy.md ]"

# ============ ROUTES ============
echo ""
echo -e "${YELLOW}=== ROUTES ===${NC}"

check "Privacy route registered" \
    "grep -q 'privacy' routes/marketing.php"

check "Terms route registered" \
    "grep -q 'terms' routes/marketing.php"

check "DPA route would be accessible" \
    "grep -q 'legal' routes/marketing.php || echo 'warn: add /legal/dpa route'"

# ============ TESTS ============
echo ""
echo -e "${YELLOW}=== TESTS ===${NC}"

check "DSAR export tests exist" \
    "[ -f tests/Feature/Services/DsarExportServiceTest.php ]"

check "Cookie consent tests exist" \
    "[ -f tests/Feature/Http/Controllers/CookieConsentControllerTest.php ]"

check "Breach notification tests exist" \
    "[ -f tests/Unit/Services/BreachNotificationServiceTest.php ]"

# ============ SUMMARY ============
echo ""
echo "========================================"
echo -e "Compliance Score: ${GREEN}$SCORE / $TOTAL${NC}"
echo "========================================"

PERCENTAGE=$((SCORE * 100 / TOTAL))
echo ""

if [ $SCORE -eq $TOTAL ]; then
    echo -e "${GREEN}✓ All compliance controls in place!${NC}"
    echo ""
    echo "Next steps:"
    echo "  1. Review /COMPLIANCE_READINESS_AUDIT_2026_03_09.md"
    echo "  2. Implement Phase 1 (COMP-001 through COMP-004)"
    echo "  3. Run this script again after implementation"
    exit 0
elif [ $PERCENTAGE -ge 80 ]; then
    echo -e "${YELLOW}⚠ Partial compliance ($PERCENTAGE%). Critical gaps must be fixed before launch.${NC}"
    echo ""
    echo "Review COMP-001, COMP-002, COMP-003, COMP-004 in:"
    echo "  /COMPLIANCE_READINESS_AUDIT_2026_03_09.md"
    exit 1
else
    echo -e "${RED}✗ Significant gaps ($PERCENTAGE%). Not ready for production.${NC}"
    exit 1
fi
