#!/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"/{constraints,foreign_keys}

# 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 table name from constraint
extract_table_name() {
    echo "$1" | sed -nE 's/.*ALTER[[:space:]]+TABLE[[:space:]]+\[?([^]]+)\]?.*/\1/p'
}

# Function to extract constraint name
extract_constraint_name() {
    echo "$1" | sed -nE 's/.*CONSTRAINT[[:space:]]+\[?([^]]+)\]?.*/\1/p'
}

# Function to process each ALTER TABLE statement
process_statement() {
    local line="$1"
    local table_name=$(extract_table_name "$line")
    local constraint_name=$(extract_constraint_name "$line")
    
    # Skip if we couldn't extract table or constraint name
    if [ -z "$table_name" ] || [ -z "$constraint_name" ]; then
        return
    fi
    
    # Determine if it's a foreign key
    if echo "$line" | grep -i "FOREIGN[[:space:]]\+KEY" >/dev/null; then
        output_dir="$BASE_DIR/foreign_keys"
    else
        output_dir="$BASE_DIR/constraints"
    fi
    
    # Clean filename and save
    clean_name=$(clean_filename "${table_name}_${constraint_name}")
    output_file="${output_dir}/${clean_name}.sql"
    echo "$line" > "$output_file"
    echo "Created: $output_file"
}

# Main processing function
extract_constraints() {
    local current_statement=""
    
    # Read the file line by line
    while IFS= read -r line || [ -n "$line" ]; do
        # Skip empty lines
        if [ -z "${line// }" ]; then
            continue
        fi
        
        # If line starts with ALTER TABLE, it's a new statement
        if echo "$line" | grep -i "^[[:space:]]*ALTER[[:space:]]\+TABLE" >/dev/null; then
            current_statement="$line"
            
            # If GO is on the same line
            if echo "$line" | grep -i "GO[[:space:]]*$" >/dev/null; then
                # Remove GO and process
                current_statement=$(echo "$current_statement" | sed 's/[[:space:]]*GO[[:space:]]*$//')
                process_statement "$current_statement"
                current_statement=""
            fi
            continue
        fi
        
        # If we find GO, process the current statement
        if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" >/dev/null; then
            if [ -n "$current_statement" ]; then
                process_statement "$current_statement"
                current_statement=""
            fi
            continue
        fi
        
        # Add line to current statement if we're collecting one
        if [ -n "$current_statement" ]; then
            current_statement+=" $line"
        fi
    done
}

# Remove comment lines starting with -- and process
echo "Extracting constraints and foreign keys..."
sed 's/--.*$//' "$SQL_FILE" | extract_constraints

echo "Constraints and foreign keys have been saved in $BASE_DIR/constraints and $BASE_DIR/foreign_keys"

# Count and list files
echo -e "\nFile counts:"
for dir in constraints foreign_keys; do
    count=$(ls -1 "$BASE_DIR/$dir"/*.sql 2>/dev/null | wc -l || echo 0)
    echo "$dir: $count files"
    
    echo -e "\nExtracted ${dir}:"
    if [ "$count" -gt 0 ]; then
        for file in "$BASE_DIR/$dir"/*.sql; do
            if [ -f "$file" ]; then
                echo "- $(basename "$file")"
            fi
        done
    fi
done