import pymysql, os, configparser

def decrypt(s):
    if not s or not s.startswith('ENC:'): return s
    hex_str = s[4:]
    key = 0xA5C3
    res = []
    for i in range(0, len(hex_str), 4):
        val = int(hex_str[i:i+4], 16)
        res.append(chr(val ^ key))
    return ''.join(res)

server, port, db, user, pwd = '85.215.144.168', 3306, 'pastelerias', 'asesoft', 'Pantera1'
for p in ['bin/db_config.ini', 'C:/GESTIGEST/db_config.ini', 'C:/AGRIGEST/db_config.ini', 'C:/CLIENTES/ASENCIO/db_config.ini', 'db_config.ini']:
    if os.path.exists(p):
        cfg = configparser.ConfigParser()
        cfg.read(p)
        if 'Database' in cfg:
            server = decrypt(cfg['Database'].get('Server', server))
            port = int(decrypt(cfg['Database'].get('Port', str(port))))
            db = decrypt(cfg['Database'].get('Database', db))
            user = decrypt(cfg['Database'].get('User_Name', user))
            pwd = decrypt(cfg['Database'].get('Password', pwd))
            print(f'Config read from {p}: server={server}, db={db}, user={user}')
            break

try:
    conn = pymysql.connect(host=server, port=port, user=user, password=pwd, database=db, charset='utf8mb4')
    print('CONNECTED SUCCESS!')
    with conn.cursor() as cur:
        print("\n--- PEDIDO 26003414 ---")
        cur.execute("SELECT id, numero_pedido, fecha_pedido, cliente_id, estado, total FROM ge_pedidos WHERE numero_pedido LIKE '%26003414%'")
        pedidos = cur.fetchall()
        for p in pedidos:
            print("Pedido:", p)

        print("\n--- ALBARANES CON NUMERO 670, 671 O VINCULADOS ---")
        cur.execute("""
            SELECT id, empresa_id, cliente_id, serie, numero, fecha, base_imponible, total, id_pedido, id_factura 
            FROM ge_albaranes 
            WHERE (numero IN (670, 671) AND serie = '26') 
               OR (id_pedido IN (SELECT id FROM ge_pedidos WHERE numero_pedido LIKE '%26003414%'))
        """)
        albaranes = cur.fetchall()
        for a in albaranes:
            print("Albarán:", a)

        alb_ids = [str(a[0]) for a in albaranes]
        if alb_ids:
            in_clause = ",".join(alb_ids)
            print("\n--- LINEAS DE LOS ALBARANES ---")
            cur.execute(f"SELECT id, id_albaran, id_articulo, descripcion, cantidad, precio, importe FROM ge_albaranes_lineas WHERE id_albaran IN ({in_clause})")
            for l in cur.fetchall():
                print("Línea:", l)

            print("\n--- BULTOS DE LOS ALBARANES ---")
            cur.execute(f"SELECT id, id_albaran, numero_bulto, codigo_sscc FROM ge_albaranes_bultos WHERE id_albaran IN ({in_clause})")
            for b in cur.fetchall():
                print("Bulto:", b)

            print("\n--- ENVIOS RELACIONADOS ---")
            cur.execute(f"SELECT id, id_albaran, numero_expedicion, estado, transportista_id, created_at FROM ge_envios WHERE id_albaran IN ({in_clause})")
            for e in cur.fetchall():
                print("Envío:", e)
except Exception as e:
    print('Error:', e)
