"""Robot Framework helper for actor compiler smoke tests.

Provides a CLI interface for Robot to invoke the actor compiler on
YAML-defined GRAPH actors and inspect compilation metadata.

Usage:
    python robot/helper_actor_compiler.py compile <yaml_file>
    python robot/helper_actor_compiler.py compile-fail <yaml_file>
    python robot/helper_actor_compiler.py metadata <yaml_file>
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

_SRC = str(Path(__file__).resolve().parents[1] / "src")
if _SRC not in sys.path:
    sys.path.insert(0, _SRC)

from cleveragents.actor.compiler import compile_actor  # noqa: E402
from cleveragents.actor.schema import ActorConfigSchema  # noqa: E402


def main() -> int:
    """Entry point called by Robot Framework ``Run Process``."""
    if len(sys.argv) < 3:
        print("Usage: helper_actor_compiler.py <compile|compile-fail|metadata> <file>")
        return 1

    command = sys.argv[1]
    yaml_path = sys.argv[2]

    if command == "compile":
        try:
            config = ActorConfigSchema.from_yaml_file(yaml_path)
            compiled = compile_actor(config)
            print(f"actor-compiler-ok: {compiled.name}")
            print(f"nodes: {len(compiled.nodes)}")
            print(f"edges: {len(compiled.edges)}")
            print(f"entry: {compiled.entry_point}")
            return 0
        except Exception as exc:
            print(f"actor-compiler-fail: {exc}")
            return 1

    if command == "compile-fail":
        try:
            config = ActorConfigSchema.from_yaml_file(yaml_path)
            compile_actor(config)
            print("actor-compiler-unexpected-success")
            return 1
        except Exception as exc:
            print(f"actor-compiler-expected-fail: {exc}")
            return 0

    if command == "metadata":
        try:
            config = ActorConfigSchema.from_yaml_file(yaml_path)
            compiled = compile_actor(config)
            meta = compiled.metadata.model_dump(mode="json")
            print(f"actor-compiler-metadata: {json.dumps(meta)}")
            return 0
        except Exception as exc:
            print(f"actor-compiler-fail: {exc}")
            return 1

    print(f"Unknown command: {command}")
    return 1


if __name__ == "__main__":
    sys.exit(main())
