# btc16m_full_sat.py
# Fully folded 16,777,216-vector HDGL covenant
# Saturated 64-vector seed lattice with unique r_dim & Ω
# Logarithmic expansion for minimal on-chain cost

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

# -------------------------
# Seed lattice instances (fully saturated)
# -------------------------
class LatticeInstance:
    def __init__(self, instance_id, D_vals, r_dim, omega):
        self.id = instance_id
        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):
        return ''.join(f"{x:08x}" for x in self.D_int)

# Generate 64 fully saturated seed vectors
SEED_LATTICE = [
    LatticeInstance(
        i+1,
        [0.0, float(i%16)/16, float((i*3)%16)/16, float((i*7)%16)/16],
        r_dim=0.05 + 0.95*i/63,      # linearly spread r_dim 0.05..1.0
        omega=1e-8 + 9e-8*i/63       # linearly spread omega 1e-8..1e-7
    )
    for i in range(64)
]

# -------------------------
# Covenant Script Generator
# -------------------------
def generate_full_hdgl_covenant(pubkey=CTv_PUBKEY, seed_lattice=SEED_LATTICE):
    script = [f"{pubkey} OP_CHECKSIGVERIFY"]

    # Embed fully saturated seed lattice
    idx_base = 100
    for li in seed_lattice:
        v_line = "0x0 0x0 0x0 0x0 OP_HDGL_VEC_ADD OP_EQUALVERIFY"
        add_line = f"{idx_base} {idx_base+1} OP_ADD {idx_base+2} OP_EQUALVERIFY"
        within_line = f"{idx_base+3} {idx_base+4} {idx_base+5} OP_WITHINVERIFY"
        param_line = f"{li.r_dim_scaled} {li.omega_fixed} OP_HDGL_PARAM_ADD OP_EQUALVERIFY"

        script.extend([v_line, add_line, within_line, param_line, ""])
        idx_base += 4

    # Logarithmic folding to reach 16,777,216 vectors
    fold_sizes = [128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536,
                  131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216]

    for size in fold_sizes:
        fold_line = f"OP_VEC_DUP {size} OP_HDGL_VEC_ADD OP_EQUALVERIFY"
        add_line = f"{idx_base} {idx_base+1} OP_ADD {idx_base+2} OP_EQUALVERIFY"
        within_line = f"{idx_base+3} {idx_base+4} {idx_base+5} OP_WITHINVERIFY"
        script.extend([fold_line, add_line, within_line, ""])
        idx_base += 4

    script.append("OP_CHECKTEMPLATEVERIFY")
    return "\n".join(script)

# -------------------------
# Generate and print
# -------------------------
if __name__ == "__main__":
    covenant_script = generate_full_hdgl_covenant()
    print("=== Fully Saturated 16,777,216-Vector HDGL Covenant ===")
    print(covenant_script)
