import openpyxl
import sys

def get_safe_str(val):
    if val is None:
        return ""
    return str(val).strip().replace("'", "''")

try:
    wb = openpyxl.load_workbook('TABLA CONTROL PAGOS 2025.xlsx', read_only=True, data_only=True)
    ws = wb.active
    
    table_name = "propietarios"
    
    # Create Table SQL
    create_sql = f"""CREATE TABLE IF NOT EXISTS {table_name} (
    id INT AUTO_INCREMENT PRIMARY KEY,
    piso VARCHAR(50),
    dpto VARCHAR(50),
    cod INT,
    nombre_propietario VARCHAR(255)
);
"""
    
    print(create_sql)
    
    # Insert SQL
    print(f"INSERT INTO {table_name} (piso, dpto, cod, nombre_propietario) VALUES")
    
    values_list = []
    
    for row in ws.iter_rows(min_row=3, values_only=True):
        piso = row[0]
        dpto = row[1]
        cod = row[2]
        nombre = row[3]
        
        # Filter out empty names/cods
        if not nombre and not cod:
            continue

        # Filter out header repetitions (e.g. where COD is "COD.")
        if str(cod).strip().upper() == "COD.":
            continue
        if str(piso).strip().upper().startswith("BLOQUE"):
            continue
            
        # Ensure COD is integer or NULL
        val_cod = "NULL"
        if cod is not None:
            try:
                # Try to parse as int to ensure validity
                int(cod) 
                val_cod = str(cod)
            except ValueError:
                # If cannot be parsed as int (and wasn't caught by header filter), skip or treat as NULL
                # In this case, better to skip if it's garbage, or set NULL if valid row but missing code
                if val_cod == "NULL": 
                     # If previous checks failed? 
                     # simpler: check if it's numeric. 
                     if isinstance(cod, (int, float)):
                         val_cod = str(int(cod))
                     else:
                         # If strictly text in a code column, likely a header or valid "NULL"
                         continue 

        val_piso = get_safe_str(piso)
        val_dpto = get_safe_str(dpto)
        val_nombre = get_safe_str(nombre)
        
        values_list.append(f"('{val_piso}', '{val_dpto}', {val_cod}, '{val_nombre}')")

    print(",\n".join(values_list) + ";")

except Exception as e:
    sys.stderr.write(f"Error: {e}\n")
    sys.exit(1)
