#!/bin/bash

# Check if input file is provided
if [ $# -ne 1 ]; then
    echo "Usage: $0 <sql_file>"
    exit 1
fi

SQL_FILE="$1"
BASE_DIR="sql_objects"

# Create directory structure
mkdir -p "$BASE_DIR/views"

# Ensure proper permissions
chmod -R 755 "$BASE_DIR"

# Function to clean filename
clean_filename() {
    # Remove brackets, convert dots and spaces to underscores, remove parentheses
    echo "$1" | sed 's/\[\|\]//g' | tr '.' '_' | tr ' ' '_' | sed 's/[()]//g' | sed 's/__*/_/g' | sed 's/_$//'
}

# Function to extract view name
extract_view_name() {
    # More flexible pattern for extracting view name
    echo "$1" | sed -n 's/.*[Cc][Rr][Ee][Aa][Tt][Ee][[:space:]]*[Vv][Ii][Ee][Ww][[:space:]]*\[\([^]]*\)\]\.\[\([^]]*\)\].*/\1.\2/p'
}

# Function to clean the input line
clean_input_line() {
    # Remove any leading/trailing whitespace and normalize spaces
    echo "$1" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | tr -s ' '
}

# Function to process each CREATE VIEW statement
process_view() {
    local current_object="$1"
    local view_name="$2"
    
    # Skip if we couldn't extract view name
    if [ -z "$view_name" ]; then
        echo "Warning: Could not extract view name from statement:"
        echo "$current_object" | head -n 1
        # Try to extract with a more lenient pattern
        view_name=$(echo "$current_object" | head -n 1 | grep -io '\[int\]\.\[[^]]*\]' | head -n 1 | sed 's/\[\|\]//g')
        if [ -z "$view_name" ]; then
            return
        fi
    fi
    
    # Clean filename and save
    clean_name=$(clean_filename "$view_name")
    output_file="$BASE_DIR/views/${clean_name}.sql"
    echo "$current_object" > "$output_file"
    echo "Created: $output_file (from view: $view_name)"
}

# Main processing function
extract_views() {
    local current_object=""
    local capture_view=false
    local view_name=""
    
    # Read the file line by line
    while IFS= read -r line || [ -n "$line" ]; do
        # Clean the line
        line=$(clean_input_line "$line")
        
        # Skip empty lines at the start of an object
        if [ -z "$line" ] && [ -z "$current_object" ]; then
            continue
        fi

        # Check if we've found a CREATE VIEW statement (case insensitive and flexible)
        if echo "$line" | grep -iE "[[:space:]]*[Cc][Rr][Ee][Aa][Tt][Ee][[:space:]]+[Vv][Ii][Ee][Ww]" >/dev/null; then
            capture_view=true
            current_object="$line"
            view_name=$(extract_view_name "$line")
            if [ -n "$view_name" ]; then
                echo "Found view: $view_name"
            fi
            continue
        fi

        # If we're capturing a view
        if $capture_view; then
            # Check if we've reached the end (GO statement)
            if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" >/dev/null; then
                # Add GO to the view definition
                current_object+=$'\n'"GO"
                process_view "$current_object" "$view_name"
                capture_view=false
                current_object=""
                view_name=""
                continue
            fi

            # Add line to current object
            current_object+=$'\n'"$line"
        fi
    done

    # Handle case where last view might not have a GO statement
    if $capture_view && [ -n "$current_object" ]; then
        process_view "$current_object" "$view_name"
    fi
}

# Pre-process the file to normalize line endings and remove comments
echo "Extracting views..."
sed 's/--.*$//; /^[[:space:]]*$/d' "$SQL_FILE" | extract_views

echo "Views have been saved in $BASE_DIR/views"

# Count and list files
count=$(ls -1 "$BASE_DIR/views"/*.sql 2>/dev/null | wc -l || echo 0)
echo -e "\nTotal views extracted: $count"

if [ "$count" -gt 0 ]; then
    echo -e "\nExtracted views:"
    for file in "$BASE_DIR/views"/*.sql; do
        if [ -f "$file" ]; then
            echo "- $(basename "$file")"
        fi
    done
fi