"""`hub_ctx` — the stable hub↔tool contract (hubApi 1).

Managed tools call `three_blocks.get_context()` and use this surface instead of
re-implementing auth or CLI discovery (see utsubo_utsbv/encode.py for the matching
standalone fallback). Keep it small: additions are fine, changes and removals
break installed tools.

Host-neutral by construction — the host adapter supplies the effective site and
the telemetry route; the host package subclasses this to add its own flavour
(Blender: `panel_category`).
"""

from __future__ import annotations

import os
import shutil
from pathlib import Path

from . import config, telemetry

HUB_API = 1


class HubContext:
    """What a managed tool may rely on. Versioned by HUB_API."""

    hub_api = HUB_API

    def __init__(self, host):
        self._host = host

    def get_token(self) -> str | None:
        """The shared `tb_` credential minted by `three-blocks login`, or None."""
        credential = config.load_credential(self.site_url())
        return credential.get("token") if credential else None

    def resolve_cli(self) -> str:
        """Absolute path to the `three-blocks` executable, or raise with a hint."""
        explicit = os.environ.get("TB_CLI")
        managed = config.config_dir() / "bin" / ("three-blocks.cmd" if os.name == "nt" else "three-blocks")
        candidate = explicit or (str(managed) if managed.is_file() else None) or shutil.which("three-blocks")
        if candidate and Path(candidate).is_file():
            return str(Path(candidate).resolve())
        raise RuntimeError(
            "Could not find the three-blocks CLI. Install it (`npm i -g three-blocks`), "
            "put `three-blocks` on PATH, or set TB_CLI to the executable path."
        )

    def site_url(self) -> str:
        return self._host.site_url()

    def report_tool_job_completed(
        self,
        *,
        tool: str,
        command_family: str,
        tool_version: str,
        output_kind: str,
    ) -> bool:
        """Report a committed managed-tool outcome without exposing auth."""
        return telemetry.report_tool_job_completed(
            site=self.site_url(),
            token=self.get_token(),
            source=self._host.EVENT_SOURCE,
            event_path=self._host.EVENT_PATH,
            tool=tool,
            command_family=command_family,
            tool_version=tool_version,
            output_kind=output_kind,
        )

    def log(self, message: str) -> None:
        print(f"three_blocks: {message}")
