"""
HX v1 Encoder

Encode HXProgram to .helix format and compress to .hxz.
"""

import base64
import json
import zlib
from pathlib import Path

from .hx_ir_v1 import HXProgram


def encode_to_helix(program: HXProgram) -> bytes:
    """
    Encode HXProgram to helix bytes.

    Format: JSON representation, UTF-8 encoded.
    """
    data = program.to_dict()
    json_str = json.dumps(data, sort_keys=True)
    return json_str.encode("utf-8")


def compress_to_hxz(encoded: bytes) -> bytes:
    """
    Compress helix bytes to .hxz format.

    Format: #HXZ_START header + base64(zlib(data))
    """
    compressed = zlib.compress(encoded, level=9)
    b64 = base64.b64encode(compressed)

    header = b"#HXZ_START\n"
    return header + b64


def decompress_hxz(hxz_bytes: bytes) -> bytes:
    """
    Decompress .hxz back to helix bytes.
    """
    # Strip header
    if hxz_bytes.startswith(b"#HXZ_START\n"):
        hxz_bytes = hxz_bytes[len(b"#HXZ_START\n"):]

    decoded = base64.b64decode(hxz_bytes)
    return zlib.decompress(decoded)


def write_hxz(path: Path, encoded_bytes: bytes):
    """Write .hxz file."""
    hxz_bytes = compress_to_hxz(encoded_bytes)
    path.write_bytes(hxz_bytes)


def read_hxz(path: Path) -> bytes:
    """Read and decompress .hxz file."""
    hxz_bytes = path.read_bytes()
    return decompress_hxz(hxz_bytes)
