"""Door controller use case built on top of the OmniLink Python engine."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Dict

from omnilink import OmniLinkEngine, TypeRegistry, load_patterns_from_file

from omnilink.use_case_loader import UseCaseConfig
from .api import close_door, get_summary, open_door

HERE = Path(__file__).resolve().parent
PATTERNS_FILE = HERE / "commands.txt"


def _handle_event(evt: Dict[str, Any]) -> Dict[str, Any]:
    template = evt.get("template")
    if not template:
        return {"ack": False, "error": "no_template"}

    door = evt.get("vars", {}).get("door")
    if not door:
        return {"ack": False, "error": "missing door"}

    handlers = {
        "open_the_[door:door]": open_door,
        "close_the_[door:door]": close_door,
    }

    handler = handlers.get(template)
    if handler is None:
        return {"ack": False, "error": f"unsupported_template:{template}"}

    try:
        result = handler(door)
    except Exception as exc:
        return {"ack": False, "error": str(exc)}
    return {"ack": True, "result": result}


def _configure(engine: OmniLinkEngine) -> None:
    engine.on(lambda _evt: True, _handle_event)


def _build_context_payload() -> str:
    try:
        return json.dumps(get_summary())
    except Exception as exc:
        return json.dumps({"error": str(exc)})


def build_use_case() -> UseCaseConfig:
    types = TypeRegistry()
    types.register("door", r"(?:front_door|back_door|garage_door)")

    templates = load_patterns_from_file(PATTERNS_FILE, types)
    return UseCaseConfig(
        types=types,
        templates=templates,
        configure=_configure,
        context_provider=_build_context_payload,
    )


USE_CASE = build_use_case()

__all__ = ["PATTERNS_FILE", "USE_CASE", "build_use_case"]
