#!/bin/bash
# =============================================================================
# URI Scheme Validation Script
# =============================================================================
# Ensures consistent URI scheme usage across the VS Code extension.
# Prevents the "file does not exist" error caused by scheme mismatches.
#
# Usage:
#   bash scripts/validate-uri-schemes.sh [file1.ts file2.ts ...]
#
# Exit codes:
#   0 - No violations found
#   1 - Violations detected
# =============================================================================

set -euo pipefail

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

# Track violations
VIOLATIONS=0

# Files to check - default to src directory if no args provided
if [ $# -eq 0 ]; then
    FILES=$(find src -name "*.ts" -type f 2>/dev/null || true)
else
    FILES="$@"
fi

if [ -z "$FILES" ]; then
    echo -e "${GREEN}✓ No files to check${NC}"
    exit 0
fi

echo "🔍 Checking URI scheme consistency..."

# Check 1: Detect hardcoded snapback:// URIs (should use snapback-snapshot:)
# This is the main bug we're preventing
echo ""
echo "Check 1: Hardcoded 'snapback://' URIs (should use 'snapback-snapshot:')"
HARDcoded_URIS=$(echo "$FILES" | xargs grep -l 'snapback://' 2>/dev/null || true)
if [ -n "$HARDcoded_URIS" ]; then
    echo -e "${RED}❌ Found hardcoded 'snapback://' URIs:${NC}"
    echo "$HARDcoded_URIS" | while read -r file; do
        # Show the actual lines with context
        grep -n 'snapback://' "$file" | head -5 | sed 's/^/  /'
    done
    echo ""
    echo -e "${YELLOW}💡 Fix: Use createSnapshotUri() from constants/uriSchemes.ts${NC}"
    echo "   or use the SNAPSHOT_SCHEME constant for the scheme name."
    VIOLATIONS=$((VIOLATIONS + 1))
else
    echo -e "${GREEN}✓ No hardcoded 'snapback://' URIs found${NC}"
fi

# Check 2: Detect direct vscode.Uri.parse with snapback-snapshot without using the utility
echo ""
echo "Check 2: Direct vscode.Uri.parse with snapback-snapshot (should use createSnapshotUri)"
DIRECT_PARSE=$(echo "$FILES" | xargs grep -l 'vscode\.Uri\.parse.*snapback-snapshot' 2>/dev/null || true)
if [ -n "$DIRECT_PARSE" ]; then
    echo -e "${YELLOW}⚠️  Found direct vscode.Uri.parse with snapback-snapshot:${NC}"
    echo "$DIRECT_PARSE" | while read -r file; do
        grep -n 'vscode\.Uri\.parse.*snapback-snapshot' "$file" | head -3 | sed 's/^/  /'
    done
    echo ""
    echo -e "${YELLOW}💡 Consider: Using createSnapshotUri() for consistency${NC}"
    # This is a warning, not an error, as some cases may be legitimate
fi

# Check 3: Ensure uriSchemes.ts is imported where needed
echo ""
echo "Check 3: Files using snapshot URIs should import from uriSchemes"
# Find files that construct snapback-snapshot URIs but don't import uriSchemes
FILES_WITH_URIS=$(echo "$FILES" | xargs grep -l 'snapback-snapshot' 2>/dev/null || true)
if [ -n "$FILES_WITH_URIS" ]; then
    for file in $FILES_WITH_URIS; do
        # Skip the uriSchemes.ts file itself
        if [[ "$(basename "$file")" == "uriSchemes.ts" ]]; then
            continue
        fi
        # Skip test files
        if [[ "$file" == *".test.ts" ]]; then
            continue
        fi
        # Check if file imports from uriSchemes
        if ! grep -q "uriSchemes" "$file" 2>/dev/null; then
            echo -e "${YELLOW}⚠️  $file uses snapback-snapshot but doesn't import from uriSchemes${NC}"
            echo "   Consider importing { SNAPSHOT_SCHEME, createSnapshotUri } from '../constants/uriSchemes'"
        fi
    done
fi

# Summary
echo ""
echo "============================================================================="
if [ $VIOLATIONS -eq 0 ]; then
    echo -e "${GREEN}✓ URI scheme validation passed${NC}"
    exit 0
else
    echo -e "${RED}❌ URI scheme validation failed with $VIOLATIONS violation(s)${NC}"
    echo ""
    echo "Common fixes:"
    echo "  1. Replace 'snapback://' with 'snapback-snapshot:' in URI strings"
    echo "  2. Use createSnapshotUri(snapshotId, filePath) instead of manual URI construction"
    echo "  3. Import SNAPSHOT_SCHEME from constants/uriSchemes for scheme references"
    exit 1
fi
