#!/usr/bin/env python3
import sys
import gzip
import os
import re

if len(sys.argv) < 2:
    print("Usage: ./mydump-structure input.sql.gz [output.sql]")
    sys.exit(1)

input_file = sys.argv[1]
is_gzipped = input_file.lower().endswith('.gz')

# Automatically generate output filename if not explicitly provided
if len(sys.argv) >= 3:
    output_file = sys.argv[2]
else:
    # Handle the path parsing dynamically
    base_name = input_file
    if is_gzipped:
        base_name = base_name[:-3]  # Strip out .gz

    root, _ = os.path.splitext(base_name)  # Separate filename from .sql extension
    output_file = f"{root}-structure.sql"

print(f"Reading input:  {input_file}")
print(f"Writing output: {output_file}")
print("Processing dump and dumping structure only...")

# Dynamically pick the correct input file opener function
file_opener = gzip.open if is_gzipped else open
open_mode = 'rt' if is_gzipped else 'r'

# Regex pattern to match 'AUTO_INCREMENT=digits' case-insensitively,
# along with any trailing whitespace/comma spaces that surround it.
auto_inc_regex = re.compile(r'\bauto_increment\s*=\s*\d+\s*', re.IGNORECASE)


skip = False

# Open the gzipped input file and a regular text output file
with file_opener(input_file, open_mode, encoding='utf-8', errors='ignore') as infile, \
     open(output_file, 'w', encoding='utf-8') as outfile:

    for line in infile:
        stripped = line.strip().lower()

        # Skip UNLOCK TABLES statements
        if stripped.startswith("unlock tables"):
            continue

        # Skip some comments
        if "dumping data for table" in stripped:
            continue

        # Skip enable/disable keys
        if "alter table" in stripped and ("disable keys" in stripped or "enable keys" in stripped):
            continue

        # Start of LOCK TABLES block
        if stripped.startswith("lock tables"):
            if not stripped.endswith(";"):
                skip = True
            continue

        # Start of INSERT INTO block
        if stripped.startswith("insert into"):
            if not stripped.endswith(";"):
                skip = True
            continue

        # Skip all lines until the end of the block (;)
        if skip:
            if stripped.endswith(";"):
                skip = False
            continue

        # Clean out the "AUTO_INCREMENT=xxx" part
        if "auto_increment" in stripped:
            line = auto_inc_regex.sub('', line)

        outfile.write(line)

print(f"Successfully extracted structure to: {output_file}")
