#!/usr/bin/env python3
"""
btc_hdgl_binary.py
Generates a fully dynamic HDGL covenant script with **binary discretization**
for superposition encoding.
"""

import math

# -------------------------------
# Constants
# -------------------------------
PHI = 1.6180339887           # golden ratio
SQRT_PHI = math.sqrt(PHI)    # threshold for binary discretization
SCALE = int(1e10)            # integer scaling for Script
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 discretize(value):
    """
    Binary discretization: 0 if < √φ else 1
    """
    return 1 if value >= SQRT_PHI else 0

def float_to_hex(val):
    return f"0x{int(val*1e10):X}"

# -------------------------------
# Generate lattice
# -------------------------------
def generate_lattice():
    lattice = []
    for i in range(32):
        val = compute_slot_value(i)
        bin_val = discretize(val)
        lattice.append(bin_val)
    return lattice

# -------------------------------
# Generate covenant
# -------------------------------
def generate_covenant(pubkey="<YOUR_PUBLIC_KEY>"):
    D_bin = generate_lattice()
    script = [f"{pubkey} OP_CHECKSIGVERIFY\n"]
    for inst in range(8):
        # slots per instance
        slots = D_bin[inst*4:(inst+1)*4]
        hex_slots = [float_to_hex(d) for d in slots]  # hex encoding for Script
        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 Binary HDGL Covenant Script ===")
    print(covenant_script)
