import math

# -------------------------
# Configuration Parameters
# -------------------------
SCALE = 10**10           # scaling φ to integer
MAX_RDIM = 255           # max r_dim_scaled
MIN_OMEGA = 10**6        # minimum Ω_fixed to prevent divergence
SLOTS_PER_INSTANCE = 4
INSTANCES = 8
CTv_PUBKEY = "<YOUR_PUBLIC_KEY>"  # Replace with actual hex pubkey

# Fibonacci for optional harmonic checks
FIBS = [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]

# -------------------------
# Lattice Representation
# -------------------------
class LatticeInstance:
    def __init__(self, instance_id, D_vals, r_dim, omega):
        self.id = instance_id
        # D_vals: list of floats, scaled to integers
        self.D_int = [int(d * SCALE) for d in D_vals]
        self.r_dim_scaled = int(r_dim * MAX_RDIM)
        self.omega_fixed = int(omega * SCALE)
    
    def pack_slots(self):
        """Pack D_int into hex for Script inclusion."""
        return ''.join(f"{x:08x}" for x in self.D_int)  # 8 hex per int

# -------------------------
# Lattice → Script Generator
# -------------------------
def generate_covenant_script(prev_lattice, next_lattice):
    """
    prev_lattice, next_lattice: list of LatticeInstance
    Returns Bitcoin Script covenant as hex string
    """
    script_lines = []
    script_lines.append(f"{CTv_PUBKEY} OP_CHECKSIGVERIFY")
    
    for prev, nxt in zip(prev_lattice, next_lattice):
        # Slot check
        prev_hex = prev.pack_slots()
        nxt_hex = nxt.pack_slots()
        script_lines.append(f"0x{prev_hex} 0x{nxt_hex} OP_HDGL_VEC_ADD OP_EQUALVERIFY")
        
        # r_dim check
        script_lines.append(f"{prev.r_dim_scaled} 1 OP_ADD {nxt.r_dim_scaled} OP_EQUALVERIFY")
        
        # Omega check
        # Slight decay allowed: nxt.omega_fixed = prev.omega_fixed * 0.95 ~ 0.99
        decay_min = int(prev.omega_fixed * 0.95)
        decay_max = int(prev.omega_fixed * 0.99)
        script_lines.append(f"{decay_min} {nxt.omega_fixed} {decay_max} OP_WITHINVERIFY")
    
    # Prevent lattice corruption
    script_lines.append("OP_CHECKTEMPLATEVERIFY")
    
    return '\n'.join(script_lines)

# -------------------------
# Example Usage
# -------------------------
if __name__ == "__main__":
    # Example lattice: two instances (simplified)
    prev_lattice = [
        LatticeInstance(1, [0.0,0.0,0.0,0.0], r_dim=0.3, omega=1e-8),
        LatticeInstance(2, [0.0,0.0,0.0,0.0], r_dim=0.4, omega=5e-9)
    ]
    
    next_lattice = [
        LatticeInstance(1, [0.0,0.0,1.0,0.0], r_dim=0.31, omega=0.95e-8),
        LatticeInstance(2, [0.0,1.0,0.0,0.0], r_dim=0.41, omega=0.95*5e-9)
    ]
    
    script = generate_covenant_script(prev_lattice, next_lattice)
    print("=== Generated Covenant Script ===")
    print(script)
