import hashlib
import os
import math

# ----------------------------
# Configuration
# ----------------------------
FIBS = [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]
MAX_SEED = 2**128 - 1
FOLD_DOUBLINGS = [2**i for i in range(25)]  # up to 33 million vectors
SEED_PARAMS = [(0, "0x156250000")]  # base omega hex values

# ----------------------------
# Helpers
# ----------------------------
def file_to_hash(filepath):
    """SHA256 hash of file as unique ID."""
    sha256 = hashlib.sha256()
    with open(filepath, "rb") as f:
        while True:
            chunk = f.read(4096)
            if not chunk:
                break
            sha256.update(chunk)
    return sha256.hexdigest()

def generate_seed(filepath):
    """Deterministic integer seed from file hash."""
    movie_hash = file_to_hash(filepath)
    seed_int = int(movie_hash[:32], 16) % MAX_SEED
    return seed_int

def generate_delta(fib_index):
    """Fibonacci delta for uniqueness."""
    return FIBS[fib_index % len(FIBS)]

# ----------------------------
# Main HDGL Covenant Generator
# ----------------------------
def generate_files_covenant(file_list):
    covenant_script = ["<YOUR_PUBLIC_KEY> OP_CHECKSIGVERIFY"]
    fib_index = 0
    
    for file_index, file_path in enumerate(file_list):
        if not os.path.exists(file_path):
            print(f"Warning: {file_path} not found, skipping...")
            continue
        
        file_hash = file_to_hash(file_path)
        seed = generate_seed(file_path)
        
        # Base vector
        covenant_script.append(f"0x{file_hash[:32]} 0x{seed:032x} OP_HDGL_VEC_ADD OP_EQUALVERIFY")
        
        # Folding loop
        vector_count = 1
        for fold in FOLD_DOUBLINGS:
            vector_count *= 2
            fib_delta = generate_delta(fib_index)
            fib_index += 1
            
            param = SEED_PARAMS[(vector_count.bit_length()-1) % len(SEED_PARAMS)]
            omega_int = int(param[1], 16)
            omega_min = omega_int + fib_delta
            omega_max = omega_int + fib_delta
            
            covenant_script.append(f"OP_VEC_DUP {vector_count//2} OP_HDGL_VEC_ADD OP_EQUALVERIFY")
            covenant_script.append(f"{vector_count//2} {vector_count//2} OP_HDGL_PARAM_ADD OP_EQUALVERIFY")
            covenant_script.append(f"{omega_int} {omega_min} {omega_max} OP_WITHINVERIFY\n")
    
    covenant_script.append("OP_CHECKTEMPLATEVERIFY")
    return "\n".join(covenant_script)

# ----------------------------
# Example usage
# ----------------------------
if __name__ == "__main__":
    # Any file types are supported
    files_to_store = [
        "movie1.mp4",
        "clip.wav",
        "document.pdf",
        "image.png",
        "presentation.pptx",
        "archive.zip"
    ]
    
    covenant = generate_files_covenant(files_to_store)
    print("=== HDGL Covenant for Mixed File Types ===")
    print(covenant)
