#!/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"

# 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 check if table is temporary
is_temporary_table() {
    local table_name="$1"
    if echo "$table_name" | grep -iE "temp|tmp|temporary|import_|viewimport_" >/dev/null; then
        return 0 # true in bash
    else
        return 1 # false in bash
    fi
}

# Function to extract CREATE TABLE statements only
extract_tables() {
    local current_object=""
    local capture_table=false
    local table_name=""
    
    # Read the file line by line
    while IFS= read -r line || [ -n "$line" ]; do
        # Check if we've found a CREATE TABLE statement
        if echo "$line" | grep -i "CREATE[[:space:]]\+TABLE" >/dev/null; then
            # Extract table name and check if it's temporary
            table_name=$(echo "$line" | sed -E 's/.*CREATE[[:space:]]+TABLE[[:space:]]+\[?([^\]]+)\]?.*/\1/')
            
            if is_temporary_table "$table_name"; then
                echo "Skipping temporary table: $table_name"
                continue
            fi
            
            capture_table=true
            current_object="$line"$'\n'
            continue
        fi

        # If we're capturing a table and find a following CREATE or ALTER statement, stop capturing
        if $capture_table; then
            if echo "$line" | grep -i "^[[:space:]]*CREATE\|^[[:space:]]*ALTER" >/dev/null; then
                # Save the current table before starting a new object
                if [ -n "$table_name" ]; then
                    clean_name=$(clean_filename "$table_name")
                    output_file="$BASE_DIR/tables/${clean_name}.sql"
                    echo "$current_object" > "$output_file"
                    echo "Created: $output_file"
                fi
                capture_table=false
                current_object=""
                table_name=""
                continue
            fi

            # Add line to current object if we're still capturing
            current_object+="$line"$'\n'

            # If we find a GO statement, save the table
            if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" >/dev/null; then
                if [ -n "$table_name" ]; then
                    clean_name=$(clean_filename "$table_name")
                    output_file="$BASE_DIR/tables/${clean_name}.sql"
                    echo "$current_object" > "$output_file"
                    echo "Created: $output_file"
                fi
                capture_table=false
                current_object=""
                table_name=""
            fi
        fi
    done < "$SQL_FILE"
}

# Remove comment lines starting with --
echo "Extracting CREATE TABLE statements..."
sed 's/--.*$//' "$SQL_FILE" | extract_tables

echo "CREATE TABLE statements have been saved in $BASE_DIR/tables/"

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

# List extracted tables
echo -e "\nExtracted tables:"
for table in "$BASE_DIR/tables"/*.sql; do
    if [ -f "$table" ]; then
        echo "- $(basename "$table")"
    fi
done