# Python Solana Client Helper
from solana.rpc.api import Client
from solana.publickey import PublicKey
from solana.account import Account
import base64
import json

SOLANA_RPC_URL = "https://api.mainnet-beta.solana.com"
client = Client(SOLANA_RPC_URL)

def fetch_hdgl_state(state_pubkey: str) -> dict:
    """
    Fetch HDGLState from Solana account.
    Returns: dict with lattice[], r_dim_scaled, omega_scaled, fold_step, strand_id
    """
    pubkey = PublicKey(state_pubkey)
    resp = client.get_account_info(pubkey)
    if not resp['result']['value']:
        raise ValueError("State account not found")
    
    data_b64 = resp['result']['value']['data'][0]
    data_bytes = base64.b64decode(data_b64)

    # Deserialize: u64 lattice[256] + u64 r_dim_scaled + u64 omega_scaled + u32 fold_step + u8 strand_id
    import struct
    lattice = list(struct.unpack("<256Q", data_bytes[:256*8]))
    r_dim_scaled, omega_scaled = struct.unpack("<QQ", data_bytes[256*8:256*8+16])
    fold_step = struct.unpack("<I", data_bytes[256*8+16:256*8+20])[0]
    strand_id = struct.unpack("<B", data_bytes[256*8+20:256*8+21])[0]

    return {
        "lattice": lattice,
        "r_dim_scaled": r_dim_scaled,
        "omega_scaled": omega_scaled,
        "fold_step": fold_step,
        "strand_id": strand_id
    }
