import openpyxl
import sys
import datetime

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

def get_safe_float(val):
    if val is None:
        return 0.0
    try:
        return float(val)
    except ValueError:
        return 0.0

try:
    wb = openpyxl.load_workbook('PAGO CHEQUES ABRIL.xlsx', read_only=True, data_only=True)
    ws = wb['CHEQUE EMITIDO']
    
    table_name = "cheques"
    
    create_sql = f"""CREATE TABLE IF NOT EXISTS {table_name} (
    id INT AUTO_INCREMENT PRIMARY KEY,
    numero_cheque VARCHAR(50),
    fecha DATE,
    comprobante VARCHAR(50),
    glosa TEXT,
    beneficiario VARCHAR(255),
    monto DECIMAL(10,2) DEFAULT 0,
    estado VARCHAR(50) DEFAULT 'Emitido',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
"""
    print(create_sql)
    print(f"INSERT INTO {table_name} (numero_cheque, fecha, comprobante, glosa, beneficiario, monto) VALUES")
    
    values_list = []
    
    # Inspection showed data starts at row 8
    # Columns: A=Cheque, B=Fecha, C=Comprobante, D=Glosa, E=Beneficiario, F=Monto
    
    for row in ws.iter_rows(min_row=8, values_only=True):
        if not row or not row[0]: # Skip empty rows or rows without cheque number
            continue
            
        cheque = get_safe_str(row[0])
        
        # Date handling
        fecha = row[1]
        fecha_str = "NULL"
        if isinstance(fecha, datetime.datetime):
            fecha_str = f"'{fecha.strftime('%Y-%m-%d')}'"
        elif isinstance(fecha, str):
             # Try to parse if string? Or just leave as is if SQL accepts it? Better safe.
             fecha_str = f"'{fecha}'"
        else:
             fecha_str = "NULL"

        comprobante = get_safe_str(row[2])
        glosa = get_safe_str(row[3])
        beneficiario = get_safe_str(row[4])
        monto = get_safe_float(row[5])
        
        val_str = f"('{cheque}', {fecha_str}, '{comprobante}', '{glosa}', '{beneficiario}', {monto})"
        values_list.append(val_str)

    if values_list:
        print(",\n".join(values_list) + ";")
    else:
        print("-- No rows found")

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