import pymysql, 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)

cfg = configparser.ConfigParser()
cfg.read('C:/GESTIGEST/db_config.ini')
server = decrypt(cfg['Database'].get('Server'))
port = int(decrypt(cfg['Database'].get('Port')))
db = decrypt(cfg['Database'].get('Database'))
user = decrypt(cfg['Database'].get('User_Name'))
pwd = decrypt(cfg['Database'].get('Password'))

conn = pymysql.connect(host=server, port=port, user=user, password=pwd, database=db, charset='utf8mb4')
with conn.cursor() as cur:
    print("=== PEDIDO 23158 ===")
    cur.execute("SELECT * FROM ge_pedidos WHERE id = 23158")
    cols = [d[0] for d in cur.description]
    row = cur.fetchone()
    print(dict(zip(cols, row)))

    cur.execute("DESCRIBE ge_pedidos_lineas")
    print("\nge_pedidos_lineas columns:")
    for r in cur.fetchall():
        print("  ", r[0])
    
    cur.execute("SELECT id, serie, numero, anulado, fecha, total, id_pedido FROM ge_albaranes WHERE id_pedido = 23158")
    print("\nge_albaranes for id_pedido = 23158:")
    for r in cur.fetchall():
        print("  ", r)

    cur.execute("SELECT * FROM ge_envios_recogidas WHERE albaran_id IN (7459, 7464)")
    cols = [d[0] for d in cur.description]
    print("\nge_envios_recogidas for 7459, 7464:")
    for r in cur.fetchall():
        print("  ", dict(zip(cols, r)))

    cur.execute("SHOW TABLES LIKE '%envio%'")
    print("\nTables with envio:", cur.fetchall())

    cur.execute("SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = %s AND (column_name LIKE '%%pedido%%' OR column_name LIKE '%%albaran%%')", (db,))
    matching = cur.fetchall()
    print(f"\nChecking {len(matching)} tables/columns for references to 7459...")
    for t, c in matching:
        try:
            cur.execute(f"SELECT COUNT(*) FROM `{t}` WHERE `{c}` = 7459")
            cnt = cur.fetchone()[0]
            if cnt > 0:
                print(f"  REFERENCE in {t}.{c}: {cnt}")
        except:
            pass
