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:
    for t in ['ob_recetas_productos', 'ob_recetas_procesos', 'ob_elaboraciones', 'ob_elaboraciones_reparto', 'ge_ordenes_produccion', 'ge_ordenes_produccion_lineas']:
        try:
            cur.execute(f"DESCRIBE `{t}`")
            print(f"\nColumns of {t}:")
            for r in cur.fetchall():
                print(f"  {r[0]} ({r[1]})")
        except Exception as e:
            print(f"Error on {t}: {e}")

    print("\n--- INGREDIENTES / MATERIAS PRIMAS DE LAS RECETAS ---")
    cur.execute("SHOW TABLES LIKE '%ingrediente%'")
    print("Ingredientes tables:", cur.fetchall())
    cur.execute("SHOW TABLES LIKE '%materia%'")
    print("Materias tables:", cur.fetchall())

    cur.execute("SELECT id, descripcion, es_masa_madre, es_masa_base, prefijo_lote FROM ob_recetas WHERE activo = 1")
    print("\nSample ob_recetas:")
    for r in cur.fetchall():
        print("  ", r)
