"""Quickstart demo for running OmniLinkEngine without any bridge."""

from __future__ import annotations

import pathlib
import sys
from typing import Any, Dict

# Allow running the script from the repository root without installing the package.
LIB_PATH = pathlib.Path(__file__).resolve().parents[3] / "src"
if str(LIB_PATH) not in sys.path:
    sys.path.insert(0, str(LIB_PATH))

from omnilink import AgentFeedback, AgentQuestion, OmniLinkEngine


def build_engine() -> OmniLinkEngine:
    """Construct a minimal engine with inline templates."""

    engine = OmniLinkEngine([
        "hello",
        "echo_[message:any]",
    ])

    def greet_handler(evt: Dict[str, Any]) -> Dict[str, Any]:
        name = evt.get("meta", {}).get("user", "friend")
        message = f"Hello, {name}!"

        # When running behind a bridge (MQTT, TCP, etc.), you can surface
        # live status updates by sending AgentFeedback through the messenger:
        # messenger = evt.get("messenger")
        # if messenger:
        #     messenger.send_feedback(AgentFeedback(message=message, kind="info"))
        return {"ack": True, "message": message}

    engine.on_template("hello", greet_handler)

    def echo_handler(evt: Dict[str, Any]) -> Dict[str, Any]:
        raw_message = evt["vars"].get("message", "")
        # Tokens are normalized to underscores during parsing, so swap them
        # back to spaces for friendlier output.
        reply = raw_message.replace("_", " ").strip()

        # Inline questions can keep operators in the loop when the engine is
        # connected to a messenger-aware bridge. For example:
        # messenger = evt.get("messenger")
        # if messenger:
        #     pending = messenger.ask_question(
        #         AgentQuestion(
        #             prompt="Send the echoed message?",
        #             choices=["yes", "no"],
        #             data={"proposal": reply},
        #         )
        #     )
        #     decision = pending.wait()
        #     messenger.send_feedback(AgentFeedback(message=f"Operator replied: {decision}"))
        return {"ack": True, "echo": reply}

    engine.on_template("echo_[message:any]", echo_handler)
    return engine


def main() -> None:
    engine = build_engine()

    hello_result = engine.handle("hello", meta={"user": "Alex"})
    print("hello ->", hello_result["result"])

    echo_result = engine.handle("echo Good morning")
    print("echo ->", echo_result["result"])

    unknown_result = engine.handle("do something else")
    print("unknown ->", unknown_result["result"])


if __name__ == "__main__":
    main()
