"""
HX v1 to Python Compiler

Generates Python module from HXProgram IR.
"""

from .hx_ir_v1 import HXProgram


def compile_to_python(program: HXProgram) -> str:
    """
    Generate Python module string from HXProgram.

    The generated module has:
    - SLOTS: list of slot names
    - VOWS: list of vow names
    - STEPS: list of step names
    - run() function that executes the ritual
    """
    slots_list = repr([s.name for s in program.slots])
    vows_list = repr([v.name for v in program.vows])
    steps_list = repr([s.name for s in program.steps])

    code = f'''"""
Generated from HX soulfile: {program.soulfile_name}
"""

SOULFILE_NAME = "{program.soulfile_name}"
SLOTS = {slots_list}
VOWS = {vows_list}
STEPS = {steps_list}


def run():
    """Execute the ritual defined in this soulfile."""
    state = {{
        "soulfile": SOULFILE_NAME,
        "slots": {{}},
        "vows_active": set(VOWS),
        "steps_executed": [],
    }}

    # Initialize memory slots
    for slot in SLOTS:
        state["slots"][slot] = None
        print(f"[HX] Memory slot initialized: {{slot}}")

    # Apply guardian vows
    for vow in VOWS:
        print(f"[HX] Guardian vow active: {{vow}}")

    # Execute ritual steps
    for step in STEPS:
        # Check vows before executing
        if "no_harm" in state["vows_active"]:
            print(f"[HX] Vow check passed for step: {{step}}")

        print(f"[HX] Executing step: {{step}}")
        state["steps_executed"].append(step)

    print(f"[HX] Ritual complete. Steps: {{len(state[\'steps_executed\'])}}")
    return state


if __name__ == "__main__":
    result = run()
    print(f"Final state: {{result}}")
'''

    return code
