"""Lower a source-aware Hybrid declaration from Syntax AST to Semantic HIR.

The compiler-facing path starts with declarations, not execution. This lesson
shows stable node identity, symbol binding, source-aware analysis, and explicit
diagnostics while keeping all numerical kernels out of scope.
"""

from __future__ import annotations

import json

from cascaqit.syntax import (
    ParameterSpec,
    SymbolBinding,
    SymbolRef,
    analyze,
    digital_block,
    program_syntax,
)

body_calls: list[float] = []


@digital_block(
    qubits=("q0",),
    parameters={"theta": ParameterSpec(unit="rad")},
    capabilities=("gate.rx",),
)
def rotate(theta: float) -> None:
    """Declare one typed Digital block without executing its function body."""
    body_calls.append(theta)


def main() -> None:
    """Build Syntax AST, bind a symbol, and inspect Semantic HIR."""
    syntax = program_syntax(
        "lesson.compiler.beginner",
        blocks=(rotate,),
        invocations=(rotate(SymbolRef("theta"), mapping={"q0": "logical.0"}),),
    )
    analysis = analyze(
        syntax,
        symbols={
            "theta": SymbolBinding(name="theta", dtype="float", unit="rad", value=0.25)
        },
        available_capabilities=("gate.rx",),
    )
    if analysis.hir is None:
        raise RuntimeError([item.to_dict() for item in analysis.diagnostics])

    payload = {
        "track": "compiler_engineer",
        "level": "beginner",
        "lesson": "syntax_hir",
        "facts": {
            "syntax_block_count": len(syntax.blocks),
            "hir_block_kinds": [block.block_kind for block in analysis.hir.blocks],
            "diagnostic_codes": [item.code for item in analysis.diagnostics],
            "syntax_hash_present": len(syntax.stable_hash()) == 64,
            "hir_hash_present": len(analysis.hir.stable_hash()) == 64,
            "function_body_executed": bool(body_calls),
        },
        "boundaries": {
            "hardware_execution": False,
            "cloud_execution": False,
            "network_accessed": False,
            "credentials_loaded": False,
        },
    }
    print(json.dumps(payload, sort_keys=True))


if __name__ == "__main__":
    main()
