#!/usr/bin/env python3
"""
btc_hdgl_full.py
HDGL covenant with shared resonance + r_dim + Ω
"""

import math

PHI = 1.6180339887
SQRT_PHI = math.sqrt(PHI)
SCALE = int(1e10)
RES_WEIGHT = 0.5
MAX_INT = 0xFFFFFFFFFFFFFFFF

FIB = [1,1]
for _ in range(2, 32):
    FIB.append(FIB[-1]+FIB[-2])
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
          53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131]

# -------------------------------
def compute_slot_value(idx):
    raw = (PHI ** (idx + 1)) * FIB[idx % len(FIB)] / PRIMES[idx % len(PRIMES)]
    return raw

def apply_resonance(slots, prev_last_slot):
    slots[0] = (slots[0] + RES_WEIGHT * prev_last_slot) / (1 + RES_WEIGHT)
    return slots

def discretize(value):
    return 1 if value >= SQRT_PHI else 0

def float_to_hex(val):
    return f"0x{min(int(val*SCALE), MAX_INT):X}"

def compute_r_dim(inst):
    # linearly map instance index to r_dim [0.3,1.0]
    return 0.3 + 0.1*inst

def compute_omega(inst):
    omega = 1 / (PHI ** (inst+1))**7
    return min(int(omega*SCALE), MAX_INT)

# -------------------------------
def generate_lattice():
    lattice = []
    prev_last_slot = 0
    for inst in range(8):
        slots = [compute_slot_value(inst*4 + i) for i in range(4)]
        slots = apply_resonance(slots, prev_last_slot)
        slots_bin = [discretize(s) for s in slots]
        lattice.extend(slots_bin)
        prev_last_slot = slots[-1]
    return lattice

# -------------------------------
def generate_covenant(pubkey="<YOUR_PUBLIC_KEY>"):
    D_bin = generate_lattice()
    script = [f"{pubkey} OP_CHECKSIGVERIFY\n"]
    for inst in range(8):
        slots = D_bin[inst*4:(inst+1)*4]
        hex_slots = [float_to_hex(d) for d in slots]
        r_dim_hex = float_to_hex(compute_r_dim(inst))
        omega_hex = float_to_hex(compute_omega(inst))
        # Vector addition
        script.append(" ".join(hex_slots) + " OP_HDGL_VEC_ADD OP_EQUALVERIFY")
        script.append(f"{100+inst*4} {101+inst*4} OP_ADD {102+inst*4} OP_EQUALVERIFY")
        script.append(f"{103+inst*4} {104+inst*4} {105+inst*4} OP_WITHINVERIFY")
        # Parameters
        script.append(f"{r_dim_hex} {omega_hex} OP_HDGL_PARAM_ADD OP_EQUALVERIFY\n")
    script.append("OP_CHECKTEMPLATEVERIFY")
    return "\n".join(script)

# -------------------------------
if __name__ == "__main__":
    covenant_script = generate_covenant()
    print("=== Generated HDGL Covenant Script with Shared Resonance + r_dim + Ω ===")
    print(covenant_script)
