"""
HX v1 Parser

Parses .hx files into HXProgram IR.
"""

import re
from pathlib import Path
from typing import Optional

from .hx_ir_v1 import HXProgram, HXMemorySlot, HXVow, HXStep


def parse_hx(source: str, filename: str = "unnamed") -> HXProgram:
    """
    Parse .hx source into HXProgram.

    Supported syntax:
        ::INIT:: <name>
        memory slot=<name>
        guardian vow=<name>
        ritual step=<name>
    """
    program = HXProgram(soulfile_name=filename)

    for line in source.split("\n"):
        line = line.strip()
        if not line or line.startswith("#"):
            continue

        # Parse ::INIT:: soulfile_name
        if line.startswith("::INIT::"):
            name = line.replace("::INIT::", "").strip()
            if name:
                program.soulfile_name = name
            continue

        # Parse memory slot=<name>
        match = re.match(r"memory\s+slot=([\w_]+)", line, re.IGNORECASE)
        if match:
            program.slots.append(HXMemorySlot(name=match.group(1)))
            continue

        # Parse guardian vow=<name>
        match = re.match(r"guardian\s+vow=([\w_]+)", line, re.IGNORECASE)
        if match:
            program.vows.append(HXVow(name=match.group(1)))
            continue

        # Parse ritual step=<name>
        match = re.match(r"ritual\s+step=([\w_]+)", line, re.IGNORECASE)
        if match:
            program.steps.append(HXStep(name=match.group(1)))
            continue

    return program


def parse_hx_file(path: Path) -> HXProgram:
    """Parse .hx file."""
    source = path.read_text(encoding="utf-8", errors="ignore")
    return parse_hx(source, filename=path.stem)
