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("--- CHEQUEO ALBARAN 7459 (26/670) ---", flush=True)
    tables_to_check = [
        ('ge_albaranes', 'id'),
        ('ge_albaranes_lineas', 'albaran_id'),
        ('ge_albaranes_bultos', 'albaran_id'),
        ('ge_albaranes_lineas_bultos', 'albaran_id'),
        ('ge_envios_recogidas', 'albaran_id'),
        ('ge_envios', 'albaran_id'),
        ('ge_facturas', 'id_albaran'),
        ('ge_facturas_lineas', 'id_albaran'),
        ('ge_stock_envasado', 'albaran_id'),
        ('ge_pedidos', 'id')
    ]
    
    for t, c in tables_to_check:
        try:
            cur.execute(f"SELECT COUNT(*) FROM `{t}` WHERE `{c}` = 7459")
            cnt = cur.fetchone()[0]
            if cnt > 0:
                print(f"  {t}.{c}: {cnt} registros", flush=True)
        except Exception as e:
            # col might not exist
            pass

    print("\n--- DETALLES LINEAS ALBARAN 7459 ---", flush=True)
    cur.execute("SELECT id, albaran_id, articulo_id, descripcion, cantidad, precio, total FROM ge_albaranes_lineas WHERE albaran_id = 7459")
    for r in cur.fetchall():
        print("  linea:", r, flush=True)

    print("\n--- DETALLES BULTOS ALBARAN 7459 ---", flush=True)
    cur.execute("SELECT * FROM ge_albaranes_bultos WHERE albaran_id = 7459")
    cols_b = [d[0] for d in cur.description]
    for r in cur.fetchall():
        print("  bulto:", dict(zip(cols_b, r)), flush=True)

    print("\n--- DETALLES RECOGIDAS ALBARAN 7459 ---", flush=True)
    cur.execute("SELECT id, pedido_id, albaran_id, cod_recogida, estado_codigo, estado_descripcion FROM ge_envios_recogidas WHERE albaran_id = 7459")
    for r in cur.fetchall():
        print("  recogida:", r, flush=True)

    print("\n--- COMPROBAR ESTADO ALBARAN 7464 (26/671) ---", flush=True)
    cur.execute("SELECT id, serie, numero, anulado, fecha, total, id_pedido FROM ge_albaranes WHERE id = 7464")
    print("  albaran 7464:", cur.fetchall(), flush=True)
    cur.execute("SELECT id, pedido_id, albaran_id, cod_recogida, estado_codigo, estado_descripcion FROM ge_envios_recogidas WHERE albaran_id = 7464")
    for r in cur.fetchall():
        print("  recogida 7464:", r, flush=True)

    print("\n--- COMPROBAR ESTADO PEDIDO 23158 ---", flush=True)
    cur.execute("SELECT id, numero_pedido, estado, cliente_id FROM ge_pedidos WHERE id = 23158")
    print("  pedido:", cur.fetchall(), flush=True)
