# filter_sql.awk

BEGIN {
    in_sql_block = 0;
    sql_command = "";
    sql_start_pattern = "ISTRUZIONE:|LOG: *istruzione:";
    target_commands_regex = "(CREATE TABLE|ALTER TABLE|DROP TABLE)";

    # If git_cutoff_date_str is empty (no Git repo or commit), set a dummy value to avoid error
    # and set perform_cutoff to false. Otherwise, it's true.
    perform_cutoff = (git_cutoff_date_str != "");
    if (!perform_cutoff) {
        git_cutoff_date_str = ""; # Ensure it's empty if not performing cutoff
    }

    current_log_timestamp_full = ""; # Initialize for each log file
}

# --- NEW AWK LOGIC FOR CUTOFF ---
# Rule 1: Always check for a new log entry header and extract its timestamp.
# This must be the first pattern rule in awk.
$0 ~ new_log_regex {
    # Always update the timestamp if it's a new log line
    current_log_timestamp_full = substr($0, 1, 23); # YYYY-MM-DD HH:MM:SS.ms (23 chars)

    # Rule 1a: If a cutoff is active AND the current log entry is OLDER than the cutoff date.
    # String comparison works for YYYY-MM-DD HH:MM:SS.ms format.
    if (perform_cutoff && current_log_timestamp_full < git_cutoff_date_str) {
        # If the current log entry is too old, discard any partially accumulated SQL command
        # that might have started before this old log line was encountered.
        in_sql_block = 0;
        sql_command = "";
        next; # Skip to the next line immediately.
    }

    # Rule 1b: If we were previously in an SQL block and this is a new, valid (not-cut-off) log entry,
    # then the previous command is complete and should be processed.
    if (in_sql_block) {
        gsub(/^[ \t\n]+|[ \t\n]+$/, "", sql_command);
        if (tolower(sql_command) ~ tolower(target_commands_regex)) {
            print sql_command "\n";
        }
        sql_command = ""; # Reset for the next command
        in_sql_block = 0; # Reset the flag
    }
}

# Rule 2: If the line starts an SQL statement (and it passed the cutoff check or no cutoff is applied).
# This rule will only run for lines that were *not* skipped by Rule 1a.
$0 ~ sql_start_pattern {
    line_content = $0;
    sub(/.*(ISTRUZIONE:|LOG: *istruzione:)[ \t]*/, "", line_content);
    sql_command = line_content;
    in_sql_block = 1;
    next; # Skip to the next line.
}

# Rule 3: If we are in an SQL block (meaning it's a continuation line for an SQL command).
# This rule will only run for lines that were *not* skipped by Rule 1a or handled by Rule 2.
in_sql_block {
    sql_command = sql_command "\n" $0;
}

END {
    # This block processes the very last command in the file if it was still accumulating
    if (in_sql_block) {
        gsub(/^[ \t\n]+|[ \t\n]+$/, "", sql_command);
        if (tolower(sql_command) ~ tolower(target_commands_regex)) {
            print sql_command "\n";
        }
    }
}