"""StatSim compiler — parse .sm models and compile to multiple backends."""

from statsim_compiler._core import BlockList, parse as _parse, expand as _expand
from statsim_compiler._core import compile_script as _compile_script
from statsim_compiler._core import compile_module as _compile_module


def parse(source: str) -> BlockList:
    """Parse .sm source and expand submodels, returning a BlockList."""
    blocks = _parse(source)
    return _expand(blocks)


def compile(blocks: BlockList, target: str = "pymc") -> dict:
    """Compile blocks to target code (module mode) with metadata.

    Returns dict with keys: code, data_names, param_names, inference_mode.
    """
    return _compile_module(blocks, target)


def compile_script(blocks: BlockList, target: str = "pymc") -> str:
    """Compile blocks to target code (script mode) — raw code string."""
    return _compile_script(blocks, target)


def model(source: str, target: str = "pymc"):
    """High-level API: parse + compile + return a runner.

    Args:
        source: StatSim model source (.sm format)
        target: Backend target ('pymc', 'stan', 'tfpjs', 'z3')

    Returns:
        Runner object with .run(), .build(), .code
    """
    blocks = parse(source)
    result = compile(blocks, target)

    if target == "pymc":
        from statsim_compiler.runners.pymc import PymcRunner
        return PymcRunner(result)

    # Generic result for other targets
    return result
