/**
 * Kimi Quota Footer (kb #85) — appends a compact Kimi usage line to the end of
 * each of Adolf's outgoing replies, via OpenClaw's `reply_payload_sending`
 * hook (docs/plugins/hooks.md: "Mutate or cancel normalized reply payloads
 * before delivery... runs after payload normalization and before channel
 * delivery, including replies routed back to the originating channel").
 *
 * Source of the numbers: the LLM-free `GET /usage` route on adolf-llm (kb
 * #62), which talks straight to Kimi's managed-usage API — no model call
 * anywhere.
 *
 * Never blocks the send path: usage is cached and refreshed in the
 * background, so a reply is at most decorated with a slightly stale
 * (<= cacheTtlMs) snapshot, and any error/timeout simply omits the footer
 * rather than delaying or breaking the message.
 *
 * Streaming caveat (verified against /app/dist in the running container,
 * kb#85): Matrix preview streaming ("draft previews finalize in place",
 * docs/concepts/streaming.md) delivers the finalized text via a direct
 * payload edit (`ctx.edit`/`onEditReceipt`) that never calls
 * deliverOutboundPayloadsInternal, so reply_payload_sending would NOT fire
 * for that path. Adolf's openclaw.json currently leaves
 * channels.matrix.streaming unset (default "off"), so every real reply goes
 * through the normal send path (sendDurableMessageBatch ->
 * deliverOutboundPayloadsInternal) where this hook does fire. If Matrix
 * streaming is ever turned on for Adolf, this footer will silently stop
 * appearing on finalized-in-place replies — re-check this comment first.
 */

import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";

const DEFAULTS = {
  enabled: true,
  usageUrl: "http://adolf-llm:8010/usage",
  cacheTtlMs: 60000, // serve a cached snapshot for up to this long
  fetchTimeoutMs: 2500, // background fetch only; never on the send path
  prefix: "— Kimi:",
};

function normalizeConfig(raw) {
  const c = raw && typeof raw === "object" ? raw : {};
  const int = (v, d) => (Number.isFinite(v) && v > 0 ? Math.floor(v) : d);
  return {
    enabled: c.enabled !== false,
    usageUrl: typeof c.usageUrl === "string" && c.usageUrl ? c.usageUrl : DEFAULTS.usageUrl,
    cacheTtlMs: int(c.cacheTtlMs, DEFAULTS.cacheTtlMs),
    fetchTimeoutMs: int(c.fetchTimeoutMs, DEFAULTS.fetchTimeoutMs),
    prefix: typeof c.prefix === "string" && c.prefix ? c.prefix : DEFAULTS.prefix,
  };
}

function pct(bucket) {
  if (!bucket || typeof bucket.pct !== "number") return null;
  return Math.round(bucket.pct);
}

function formatFooter(usage, prefix) {
  if (!usage) return null;
  const parts = [];
  const h5 = pct(usage.window_5h);
  const wk = pct(usage.weekly);
  const d7 = pct(usage.window_7d);
  if (h5 !== null) parts.push(`5h ${h5}%`);
  if (wk !== null) parts.push(`weekly ${wk}%`);
  if (d7 !== null) parts.push(`7d ${d7}%`);
  if (parts.length === 0) return null;
  return `${prefix} ${parts.join(" · ")}`;
}

export default definePluginEntry({
  id: "kimi-quota-footer",
  name: "Kimi Quota Footer",
  description: "Appends a compact Kimi usage line to the end of each outgoing reply.",
  register(api) {
    const cfg = normalizeConfig(api.pluginConfig);

    // Non-blocking cache: the send path never awaits the network. When the
    // snapshot is stale we kick a background refresh and keep using the last
    // known one; a quota readout tolerates being a minute stale.
    let cache = { usage: null, ts: 0 };
    let refreshing = false;

    async function refresh() {
      if (refreshing) return;
      refreshing = true;
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), cfg.fetchTimeoutMs);
      try {
        const res = await fetch(cfg.usageUrl, { signal: controller.signal });
        if (!res.ok) throw new Error(`/usage HTTP ${res.status}`);
        cache = { usage: await res.json(), ts: Date.now() };
      } catch (e) {
        api.logger?.debug?.(`kimi-quota-footer: usage refresh failed (${e?.message || e})`);
      } finally {
        clearTimeout(timer);
        refreshing = false;
      }
    }

    // Warm the cache at startup so the first reply already carries a footer.
    refresh();

    // Resolve the current footer, refreshing usage without blocking the send
    // path (one-shot blocking only on a cold cache).
    async function currentFooter() {
      if (!cache.usage) {
        await refresh();
      } else if (Date.now() - cache.ts > cfg.cacheTtlMs) {
        refresh();
      }
      return formatFooter(cache.usage, cfg.prefix);
    }

    api.on("reply_payload_sending", async (event) => {
      try {
        if (!cfg.enabled) return;
        const payload = event?.payload;
        const text = payload?.text;
        if (typeof text !== "string" || text.trim().length === 0) return;
        const footer = await currentFooter();
        if (!footer || text.includes(footer)) return;
        return { payload: { ...payload, text: `${text}\n\n${footer}` } };
      } catch (e) {
        api.logger?.warn?.(`kimi-quota-footer: hook failed (${e?.message || e})`);
      }
    });
  },
});
