#!/usr/bin/env python3
"""
btc_hdgl_resonance.py
Generates a dynamic HDGL covenant Script with
binary discretization + shared cross-instance resonance.
"""

import math

# -------------------------------
# Constants
PHI = 1.6180339887
SQRT_PHI = math.sqrt(PHI)
SCALE = int(1e10)
RES_WEIGHT = 0.5  # cross-instance resonance

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]

# -------------------------------
# Helpers
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):
    # apply resonance to first slot of current instance
    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{int(val*SCALE):X}"

# -------------------------------
# Generate lattice
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)]
        # apply shared resonance from previous instance
        slots = apply_resonance(slots, prev_last_slot)
        # discretize
        slots_bin = [discretize(s) for s in slots]
        lattice.extend(slots_bin)
        prev_last_slot = slots[-1]  # save last slot for next instance
    return lattice

# -------------------------------
# Generate covenant script
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]
        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\n")
    script.append("OP_CHECKTEMPLATEVERIFY")
    return "\n".join(script)

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