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("=== BUSCANDO EN TODAS LAS TABLAS DEL SISTEMA REFERENCIAS A 7459 ===")
    cur.execute("SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = %s", (db,))
    cols = cur.fetchall()
    for t, c in cols:
        try:
            cur.execute(f"SELECT COUNT(*) FROM `{t}` WHERE `{c}` = 7459")
            cnt = cur.fetchone()[0]
            if cnt > 0:
                print(f"  {t}.{c} = {cnt}")
        except:
            pass

    print("\n=== BUSCANDO EN TODAS LAS TABLAS DEL SISTEMA REFERENCIAS A 7464 ===")
    for t, c in cols:
        try:
            cur.execute(f"SELECT COUNT(*) FROM `{t}` WHERE `{c}` = 7464")
            cnt = cur.fetchone()[0]
            if cnt > 0:
                print(f"  {t}.{c} = {cnt}")
        except:
            pass

    print("\n=== BUSCANDO EN TODAS LAS TABLAS DEL SISTEMA REFERENCIAS AL PEDIDO 23158 ===")
    for t, c in cols:
        try:
            cur.execute(f"SELECT COUNT(*) FROM `{t}` WHERE `{c}` = 23158")
            cnt = cur.fetchone()[0]
            if cnt > 0:
                print(f"  {t}.{c} = {cnt}")
        except:
            pass
