import hashlib

# ---------------------------------------------------
# Helper Functions
# ---------------------------------------------------

def sha256_hex(data: bytes) -> str:
    """Compute SHA256 and return hex string."""
    return hashlib.sha256(data).hexdigest()

def format_push(data: str) -> str:
    """
    Format a hex string or integer as Bitcoin Script push.
    """
    if isinstance(data, int):
        return str(data)
    elif data.startswith("0x"):
        return data
    else:
        return "0x" + data

# ---------------------------------------------------
# Movie Entry Generator
# ---------------------------------------------------

def movie_entry(movie_id: str, seed: str, rule: str, delta: str) -> str:
    """
    Return covenant snippet for a single movie.
    """
    return f"""{format_push(movie_id)} {format_push(seed)} {format_push(rule)} {format_push(delta)} OP_HDGL_VEC_ADD OP_EQUALVERIFY"""

# ---------------------------------------------------
# Global Registry Covenant
# ---------------------------------------------------

def build_global_registry(movies: list) -> str:
    """
    Build the shared global registry covenant.
    """
    entries = []
    for movie in movies:
        movie_id = sha256_hex(movie["title"].encode())
        entries.append(
            movie_entry(movie_id, movie["seed"], movie["rule"], movie["delta"])
        )
    body = "\n".join(entries)
    return f"""
=== HDGL Global Movie Registry Covenant ===
<GLOBAL_REGISTRY_PUBKEY> OP_CHECKSIGVERIFY

{body}

OP_CHECKTEMPLATEVERIFY
"""

# ---------------------------------------------------
# Private Covenant Extension
# ---------------------------------------------------

def build_private_extension(movies: list, user_pubkey: str) -> str:
    """
    Build a private covenant for one user’s movies.
    """
    entries = []
    for movie in movies:
        movie_id = sha256_hex(movie["title"].encode())
        entries.append(
            movie_entry(movie_id, movie["seed"], movie["rule"], movie["delta"])
        )
    body = "\n".join(entries)
    return f"""
=== HDGL Private Extension Covenant ===
{user_pubkey} OP_CHECKSIGVERIFY

{body}

OP_CHECKTEMPLATEVERIFY
"""

# ---------------------------------------------------
# Example Usage
# ---------------------------------------------------

if __name__ == "__main__":
    shared_movies = [
        {"title": "The Matrix", "seed": "0xSEED01", "rule": "0xRULEA", "delta": "0xDELTA01"},
        {"title": "Inception", "seed": "0xSEED02", "rule": "0xRULEB", "delta": "0xDELTA02"},
    ]

    private_movies = [
        {"title": "Family_HomeVideo1", "seed": "0xSEED05", "rule": "0xRULEX", "delta": "0xDELTA17"},
        {"title": "SecretProject", "seed": "0xSEED03", "rule": "0xRULEY", "delta": "0xDELTA2A"},
    ]

    global_registry = build_global_registry(shared_movies)
    private_extension = build_private_extension(private_movies, "<USER_PUBKEY>")

    print(global_registry)
    print(private_extension)
