"""Event wiring and initialization for Knowledge Explorer UI.

[feature: knowledge-ui, invariant: 1]
"""

import asyncio

import state
import render
import controls
import ws_handler


def _wrap_async(coro_fn):
    """Wrap an async handler so JS click events schedule the coroutine."""

    def handler(event):
        asyncio.ensure_future(coro_fn(event))

    return handler


async def init():
    """Initialize the Knowledge Explorer UI."""
    try:
        from js import document, window
        from pyodide.ffi import create_proxy
    except ImportError:
        return

    # Wire login button
    login_btn = document.getElementById("login-btn")
    if login_btn:
        login_btn.addEventListener(
            "click", create_proxy(_wrap_async(controls.on_login))
        )

    # Wire search button
    search_btn = document.getElementById("search-btn")
    if search_btn:
        search_btn.addEventListener(
            "click", create_proxy(_wrap_async(controls.on_search))
        )

    # Wire ingest button
    ingest_btn = document.getElementById("ingest-btn")
    if ingest_btn:
        ingest_btn.addEventListener(
            "click", create_proxy(_wrap_async(controls.on_ingest))
        )

    # Wire refresh button
    refresh_btn = document.getElementById("refresh-btn")
    if refresh_btn:
        refresh_btn.addEventListener(
            "click", create_proxy(_wrap_async(controls.on_refresh))
        )

    # Wire functor dropdown change
    functor_select = document.getElementById("ingest-functor")
    if functor_select:
        functor_select.addEventListener(
            "change", create_proxy(_wrap_async(controls.on_functor_change))
        )

    render.render_status("Knowledge Explorer ready. Please log in.", "info")

    # Auto-connect WebSocket if token exists
    token = state.get_token()
    if token:
        ws_url = f"ws://{window.location.host}/ws"
        await ws_handler.connect(ws_url, token)


# Schedule async initialization
asyncio.ensure_future(init())
