#!/usr/bin/env python3
"""
btc_hdgl_dynamic.py
Generates a fully dynamic, φ-based HDGL covenant script for Bitcoin Script.
Computes 32-slot lattice (8 instances × 4 slots) using φ, Fibonacci, and primes.
"""

import math

# -------------------------------
# Constants
# -------------------------------
SCALE = int(1e10)            # integer scaling
PHI = 1.6180339887           # golden ratio
SQRT_PHI = math.sqrt(PHI)    # binary discretization threshold

# Fibonacci numbers (first 32)
FIB = [1,1]
for _ in range(2, 32):
    FIB.append(FIB[-1]+FIB[-2])

# First 32 primes
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 clamp(value, min_val, max_val):
    return max(min_val, min(max_val, value))

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

def compute_slot_value(instance_idx, slot_idx):
    """
    Compute a φ/Fibonacci/prime-based D-value.
    Formula example: D = φ^slot_idx * FIB[slot_idx] / PRIMES[slot_idx]
    Scaled for Script integer representation.
    """
    fib = FIB[slot_idx % len(FIB)]
    prime = PRIMES[slot_idx % len(PRIMES)]
    raw = (PHI ** (slot_idx + 1)) * fib / prime
    return raw

# -------------------------------
# Dynamic lattice generation
# -------------------------------
def generate_lattice():
    D_values = []
    for inst in range(8):
        for slot in range(4):
            idx = inst*4 + slot
            D_values.append(compute_slot_value(inst, idx))
    return D_values

# -------------------------------
# Generate covenant
# -------------------------------
def generate_covenant(public_key="<YOUR_PUBLIC_KEY>"):
    D_float = generate_lattice()
    r_dim_list = [0.3 + 0.1*i for i in range(8)]
    omega_list = [1/(PHI**(i+1))**7 for i in range(8)]

    script = [f"{public_key} OP_CHECKSIGVERIFY\n"]
    for inst in range(8):
        slots = D_float[inst*4:(inst+1)*4]
        r_dim = clamp(r_dim_list[inst], 0.0, 1.0)
        omega = max(omega_list[inst], 1e-10)

        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 Dynamic HDGL Covenant Script ===")
    print(covenant_script)
