import os

FIBS = [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]

def file_to_vectors(file_path, chunk_size=128):
    """Encode file into HDGL vectors."""
    vectors = []
    with open(file_path, "rb") as f:
        data = f.read()
    for i in range(0, len(data), chunk_size):
        chunk = data[i:i+chunk_size]
        # Convert chunk to integer
        vec_int = int.from_bytes(chunk, "big")
        # Apply Fibonacci delta
        fib_delta = FIBS[(i // chunk_size) % len(FIBS)]
        vec_int += fib_delta
        vectors.append(vec_int)
    return vectors

def vectors_to_covenant(vectors):
    """Generate compact HDGL covenant."""
    lines = ["<YOUR_PUBLIC_KEY> OP_CHECKSIGVERIFY"]
    for i, v in enumerate(vectors):
        # For compactness, we only store single delta vector
        lines.append(f"{v} {v} {v} OP_WITHINVERIFY")
    lines.append("OP_CHECKTEMPLATEVERIFY")
    return "\n".join(lines)

def covenant_to_vectors(covenant_text):
    """Parse covenant back into vectors."""
    vectors = []
    for line in covenant_text.splitlines():
        if "OP_WITHINVERIFY" in line:
            parts = line.split()
            v = int(parts[0])
            vectors.append(v)
    return vectors

def vectors_to_file(vectors, output_path, chunk_size=128):
    """Reconstruct file from vectors."""
    bytes_out = bytearray()
    for i, vec in enumerate(vectors):
        fib_delta = FIBS[i % len(FIBS)]
        vec -= fib_delta
        chunk_bytes = vec.to_bytes(chunk_size, "big")
        bytes_out.extend(chunk_bytes)
    # Trim extra padding
    bytes_out = bytes_out.rstrip(b'\x00')
    with open(output_path, "wb") as f:
        f.write(bytes_out)
