#!/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"/{tables,views,procedures,constraints,indexes,alter_tables}

# Function to clean filename
clean_filename() {
    echo "$1" | sed 's/\[\|\]//g' | tr '.' '_'
}

# Function to extract SQL objects and save to files
extract_objects() {
    local current_object=""
    local object_type=""
    local object_name=""
    local table_name=""
    
    # Read the file line by line
    while IFS= read -r line || [ -n "$line" ]; do
        # Skip empty lines at the start
        if [ -z "$current_object" ] && [ -z "${line// }" ]; then
            continue
        fi

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

        # Check if we've reached the end of an object (GO statement)
        if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" >/dev/null; then
            # Determine object type and name
            if echo "$current_object" | grep -i "CREATE[[:space:]]\+TABLE" >/dev/null; then
                object_type="tables"
                object_name=$(echo "$current_object" | grep -i "CREATE[[:space:]]\+TABLE" | sed -E 's/.*CREATE[[:space:]]+TABLE[[:space:]]+\[?([^\]]+)\]?.*/\1/')
            elif echo "$current_object" | grep -i "CREATE[[:space:]]\+VIEW" >/dev/null; then
                object_type="views"
                object_name=$(echo "$current_object" | grep -i "CREATE[[:space:]]\+VIEW" | sed -E 's/.*CREATE[[:space:]]+VIEW[[:space:]]+\[?([^\]]+)\]?.*/\1/')
            elif echo "$current_object" | grep -i "CREATE[[:space:]]\+PROC" >/dev/null; then
                object_type="procedures"
                object_name=$(echo "$current_object" | grep -i "CREATE[[:space:]]\+PROC[[:space:]EDURE]*" | sed -E 's/.*CREATE[[:space:]]+PROC[[:space:]EDURE]*[[:space:]]+\[?([^\]]+)\]?.*/\1/')
            elif echo "$current_object" | grep -i "ALTER[[:space:]]\+TABLE" >/dev/null; then
                # Extract table name and constraint name if it exists
                table_name=$(echo "$current_object" | grep -i "ALTER[[:space:]]\+TABLE" | sed -E 's/.*ALTER[[:space:]]+TABLE[[:space:]]+\[?([^\]]+)\]?.*/\1/')
                
                if echo "$current_object" | grep -i "ADD[[:space:]]\+CONSTRAINT" >/dev/null; then
                    object_type="constraints"
                    object_name=$(echo "$current_object" | grep -i "CONSTRAINT" | sed -E 's/.*CONSTRAINT[[:space:]]+\[?([^\]]+)\]?.*/\1/')
                else
                    object_type="alter_tables"
                    object_name="${table_name}_alter_$(date +%s%N | cut -b1-5)"
                fi
            elif echo "$current_object" | grep -i "CREATE.*INDEX" >/dev/null; then
                object_type="indexes"
                object_name=$(echo "$current_object" | grep -i "INDEX" | sed -E 's/.*INDEX[[:space:]]+\[?([^\]]+)\]?.*/\1/')
            fi

            # If we identified an object type and name, save it
            if [ -n "$object_type" ] && [ -n "$object_name" ]; then
                # Clean the filename
                clean_name=$(clean_filename "$object_name")
                output_file="$BASE_DIR/$object_type/$clean_name.sql"

                # For alter_tables, make sure we don't overwrite existing files
                if [ "$object_type" = "alter_tables" ]; then
                    counter=1
                    base_file="$BASE_DIR/$object_type/$clean_name"
                    while [ -f "${base_file}.sql" ]; do
                        clean_name="${clean_name}_${counter}"
                        counter=$((counter + 1))
                    done
                    output_file="$base_file.sql"
                fi

                # Save the object to file
                echo "$current_object" > "$output_file"
                echo "Created: $output_file"
            fi

            # Reset for next object
            current_object=""
            object_type=""
            object_name=""
            table_name=""
        fi
    done < "$SQL_FILE"
}

# Remove comment lines starting with --
echo "Removing comments and processing SQL file..."
sed 's/--.*$//' "$SQL_FILE" | extract_objects

echo "SQL objects have been organized in the $BASE_DIR directory."
echo "
Directory structure:
$BASE_DIR/
├── tables/
├── views/
├── procedures/
├── constraints/
├── indexes/
└── alter_tables/"

# Count files in each directory
echo -e "\nFile counts:"
for dir in tables views procedures constraints indexes alter_tables; do
    count=$(ls -1 "$BASE_DIR/$dir"/*.sql 2>/dev/null | wc -l)
    echo "$dir: $count files"
done