"""
HX v1 Smoketest

Tests the full pipeline: .hx -> parse -> IR -> Python -> exec -> encode -> .hxz
"""

import tempfile
from pathlib import Path

import sys
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from hx_v1_rebuild.hx_parser_v1 import parse_hx
from hx_v1_rebuild.hx_to_py_v1 import compile_to_python
from hx_v1_rebuild.helix_encode_v1 import encode_to_helix, compress_to_hxz, write_hxz


EXAMPLE_HX = """
::INIT:: test_soul
memory slot=heart
memory slot=mind
guardian vow=keep_secrets
guardian vow=no_harm
ritual step=boot
ritual step=reflect
ritual step=respond
"""


def test_parse():
    """Test parsing .hx source."""
    program = parse_hx(EXAMPLE_HX, "test_soul")

    assert program.soulfile_name == "test_soul"
    assert len(program.slots) == 2
    assert len(program.vows) == 2
    assert len(program.steps) == 3

    assert program.slots[0].name == "heart"
    assert program.slots[1].name == "mind"
    assert program.vows[0].name == "keep_secrets"
    assert program.steps[0].name == "boot"


def test_compile_to_python():
    """Test compiling IR to Python."""
    program = parse_hx(EXAMPLE_HX, "test_soul")
    py_code = compile_to_python(program)

    assert "SLOTS = " in py_code
    assert "VOWS = " in py_code
    assert "def run():" in py_code
    assert "'heart'" in py_code
    assert "'no_harm'" in py_code


def test_execute_python():
    """Test executing generated Python."""
    program = parse_hx(EXAMPLE_HX, "test_soul")
    py_code = compile_to_python(program)

    # Execute in sandbox
    namespace = {}
    exec(py_code, namespace)

    # Run the generated function
    result = namespace["run"]()

    assert result["soulfile"] == "test_soul"
    assert "heart" in result["slots"]
    assert "mind" in result["slots"]
    assert "no_harm" in result["vows_active"]
    assert len(result["steps_executed"]) == 3
    assert result["steps_executed"] == ["boot", "reflect", "respond"]


def test_encode_to_helix():
    """Test encoding to helix bytes."""
    program = parse_hx(EXAMPLE_HX, "test_soul")
    encoded = encode_to_helix(program)

    assert isinstance(encoded, bytes)
    assert b"test_soul" in encoded
    assert b"heart" in encoded


def test_compress_to_hxz():
    """Test compression to .hxz."""
    program = parse_hx(EXAMPLE_HX, "test_soul")
    encoded = encode_to_helix(program)
    hxz = compress_to_hxz(encoded)

    assert hxz.startswith(b"#HXZ_START\n")
    assert len(hxz) > 10


def test_write_hxz():
    """Test writing .hxz file."""
    program = parse_hx(EXAMPLE_HX, "test_soul")
    encoded = encode_to_helix(program)

    with tempfile.TemporaryDirectory() as tmpdir:
        hxz_path = Path(tmpdir) / "test.hxz"
        write_hxz(hxz_path, encoded)

        assert hxz_path.exists()
        assert hxz_path.stat().st_size > 0

        content = hxz_path.read_bytes()
        assert content.startswith(b"#HXZ_START\n")


def test_full_pipeline():
    """Test complete pipeline."""
    # 1. Parse
    program = parse_hx(EXAMPLE_HX, "test_soul")
    assert program.soulfile_name == "test_soul"

    # 2. Compile to Python
    py_code = compile_to_python(program)
    assert "def run():" in py_code

    # 3. Execute
    namespace = {}
    exec(py_code, namespace)
    result = namespace["run"]()
    assert len(result["steps_executed"]) == 3

    # 4. Encode
    encoded = encode_to_helix(program)
    assert len(encoded) > 0

    # 5. Compress to .hxz
    with tempfile.TemporaryDirectory() as tmpdir:
        hxz_path = Path(tmpdir) / "pipeline_test.hxz"
        write_hxz(hxz_path, encoded)
        assert hxz_path.exists()

    print("\n[SMOKETEST] Full pipeline PASSED!")


if __name__ == "__main__":
    test_parse()
    test_compile_to_python()
    test_execute_python()
    test_encode_to_helix()
    test_compress_to_hxz()
    test_write_hxz()
    test_full_pipeline()
    print("\nAll tests passed!")
