
def process_excel(file, user):
    tipo = None  # Inicializa la variable para identificar el tipo de archivo

    try:
        # Intentar leer la hoja 'CONSOLIDADO' (Revisiones)
        df = pd.read_excel(file, sheet_name='CONSOLIDADO')
        tipo = "Revisiones"
    except Exception:
        try:
            # Intentar leer la hoja 'Aprobados' (Materiales)
            df = pd.read_excel(file, sheet_name='Aprobados')
            tipo = "Materiales"
        except Exception:
            return {"success": False, "message": "No se pudo identificar el tipo de archivo. Asegúrese de que contenga la hoja 'CONSOLIDADO' o 'Aprobados'."}

    try:
        # Limpieza de datos
        if tipo == 'Revisiones':
            df = clean_revisiones(df)
        else:
            df = clean_materiales(df)
    except Exception as e:
        return {"success": False, "message": f"Error en la transformación de datos: {e}"}

    print(f"✅ Tipo detectado: {tipo}")

    # Configuración de conexión SQL Server
    # Cargar variables de entorno
    load_dotenv()

    # Asignar credenciales desde el archivo .env
    server = os.getenv('DB_HOST')
    database = os.getenv('DB_NAME')
    username = os.getenv('DB_USER')
    password = os.getenv('DB_PASSWORD')

    try:
        conn = pyodbc.connect(
            f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
        )
        cursor = conn.cursor()

        print(f"✅ Conexion exitosa a Base de Datos")
    except Exception as e:
        return {"success": False, "message": f"Error de conexión a SQL Server: {e}"}

    # 🔹 Query de INSERT con placeholders
    if tipo == 'Revisiones':
            sql = """
            INSERT INTO REVISIONES (
                [FECHA REVISION], [FECHA FIN SISTEMA], [ACTA NUMERO], [NUMERO REVISION], 
                [CUENTA PAGO], [CUENTA USUARIO], [NUMERO PROCESO], ZONA, MUNICIPIO, 
                OBSERVACIONES, PROCESO, TIPO, MOTIVO, [CODIGO REVISOR], HALLAZGO, DIRECCION, 
                TRAFO, [NUMERO MEDIDOR], [TIPO LECTURA], [CANTIDAD ANEXOS], [TIPO DOCUMENTO], 
                ITEM, CANTIDAD, [VALOR UNITARIO], [VALOR TOTAL], [INDICADOR COBRO], 
                [IDMATERIAL INDICADOR], TARIFA, CONTRATISTA, ACTIVIDAD, LINEA, [PLAN TACTICO], ANEXOID
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """
    else:
        sql = """
    INSERT INTO MATERIALES (
        [ACTA NUMERO], [NUMERO REVISION], [FECHA REVISION], IDMATERIAL, MUNICIPIO, ITEM, CANTIDAD, 
        ZONA, [VALOR UNITARIO], [VALOR TOTAL], CONTRATISTA, ACTIVIDAD, LINEA, 
        [PLAN TACTICO], [CUENTA PAGO], ANEXOID
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    """
    progress, _ = UploadProgress.objects.get_or_create(user=user)
    progress.progress = 0
    progress.save()
    total_rows = len(df)

    try:
        for i, row in df.iterrows():
            cursor.execute(sql, tuple(row))
            progress.progress = int((i / total_rows) * 100)
            progress.save()
        
        conn.commit() 

        print("✅ Anexo Cargado De forma Existosa.")
    except Exception as e:
        return {"success": False, "message": f"Error al insertar en la base de datos: {e}"}
    
    progress.progress = 0
    progress.save()

    # 🔹 Cerrar conexión
    cursor.close()
    conn.close()
    print("🔌 Conexión cerrada correctamente.")

    return {"success": True, "tipo": tipo}
