/**
 * opencode-bru-usage · TUI 插件入口(OpenCode V2 CLI 插件 API)
 * 在会话侧栏渲染蓝区火山网关(BlueRegionUsage)token 用量 KPI:
 *   蓝区火山 token 用量
 *   24.7M tokens
 *   请求 173 · 缓存 96.5%
 *
 *   日  48.98 / 150   ████████████  33%
 *   周  55.30 / 500   █░░░░░░░░░░░  11%
 *   月 120.44 / 1000  █░░░░░░░░░░░  12%
 *
 *   · glm-5.3           99%
 *
 *   14:32 更新
 * 数据每 10 分钟自动刷新;未配置 / 加载中 / 失败均有独立展示态。
 * 另监听 session.idle:日/周/月限额 80%/100% 弹 toast 告警(V2 server 插件无 toast API,迁到 TUI 端)。
 */
import { createSignal, onCleanup } from "solid-js"
import { Plugin, usePlugin } from "@opencode/plugin/tui"
import {
  resolveConfig,
  fetchCreditWindows,
  fetchKpiBundle,
  abbrev,
  creditText,
  hitRate,
  bar,
  USAGE_WINDOWS,
  type KpiSnapshot,
  type UsageWindow,
} from "./shared.js"

type WidgetState =
  | { status: "unconfigured"; missing: string[] }
  | { status: "loading" }
  | { status: "error"; message: string }
  | {
      status: "ok"
      snap: KpiSnapshot
      credits: Record<UsageWindow, number | null>
      limits: Record<"daily" | "weekly" | "monthly", number | null>
    }

const LIMIT_KEYS: Record<UsageWindow, "dailyCreditLimit" | "weeklyCreditLimit" | "monthlyCreditLimit"> = {
  today: "dailyCreditLimit",
  week: "weeklyCreditLimit",
  month: "monthlyCreditLimit",
}

function trimMessage(msg: string, max = 48): string {
  const oneLine = String(msg || "").split("\n")[0]
  return oneLine.length > max ? oneLine.slice(0, max - 1) + "…" : oneLine
}

function timeOfDay(ms: number): string {
  const d = new Date(ms)
  const p = (x: number) => (x < 10 ? "0" : "") + x
  return p(d.getHours()) + ":" + p(d.getMinutes())
}

/** 刷新间隔(分钟):options.refreshMinutes,最小 1,默认 10 */
function refreshMinutesOf(options?: Record<string, unknown>): number {
  const v = Number((options as any)?.refreshMinutes)
  return Number.isFinite(v) && v >= 1 ? v : 10
}

function BruUsageWidget(props: { options?: Record<string, unknown> }) {
  const context = usePlugin()
  const theme = () => context.theme
  const [state, setState] = createSignal<WidgetState>({ status: "loading" })

  async function refresh() {
    // 每次刷新重新解析配置:bru_usage login / 手动改配置后,侧栏可在下一轮自愈
    const resolved = resolveConfig(props.options)
    if (!resolved.ok) {
      setState({ status: "unconfigured", missing: resolved.missing })
      return
    }
    try {
      const { snap, credits } = await fetchKpiBundle(resolved.config)
      setState({
        status: "ok",
        snap,
        credits,
        limits: {
          daily: resolved.config.dailyCreditLimit,
          weekly: resolved.config.weeklyCreditLimit,
          monthly: resolved.config.monthlyCreditLimit,
        },
      })
    } catch (e: any) {
      setState({ status: "error", message: e?.message || String(e) })
    }
  }

  refresh()
  const timer = setInterval(refresh, refreshMinutesOf(props.options) * 60_000)
  onCleanup(() => clearInterval(timer))

  const snap = () => {
    const s = state()
    return s.status === "ok" ? s.snap : null
  }
  const colorFor = (pct: number) => {
    if (pct >= 100) return theme().text.feedback.error.base
    if (pct >= 80) return theme().text.feedback.warning.base
    return theme().text.feedback.success.base
  }

  return (
    <box flexDirection="column" gap={1} flexShrink={0}>
      <text fg={theme().text.base}>蓝区火山 token 用量</text>
      {(() => {
        const s = state()
        if (s.status === "unconfigured") {
          return (
            <box flexDirection="column">
              <text fg={theme().text.muted}>未配置:{s.missing.join("、")}</text>
              <text fg={theme().text.muted}>设 BRU_API_KEY,或项目 opencode.json 配网关 provider</text>
            </box>
          )
        }
        if (s.status === "loading") {
          return <text fg={theme().text.muted}>加载中…</text>
        }
        if (s.status === "error") {
          return <text fg={theme().text.feedback.error.base}>查询失败:{trimMessage(s.message)}</text>
        }
        const k = s.snap
        const creditLimitKeys = { today: "daily", week: "weekly", month: "monthly" } as const
        const labels = { today: "日", week: "周", month: "月" } as const
        const creditRows = (["today", "week", "month"] as const).map((w) => {
          const limit = s.limits[creditLimitKeys[w]]
          const credit = s.credits[w]
          const label = labels[w]
          if (credit === null || !Number.isFinite(credit)) {
            return { fg: theme().text.muted, left: label + "      --", right: "" }
          }
          if (limit === null) {
            return { fg: theme().text.base, left: label + " " + creditText(credit).padStart(6), right: "--" }
          }
          const p = (credit / limit) * 100
          return {
            fg: colorFor(p),
            left: label + " " + creditText(credit).padStart(6) + " / " + limit,
            right: bar(p, 12) + " " + (p.toFixed(0) + "%").padStart(4),
          }
        })
        const top = k.models.slice(0, 2)
        return (
          <box flexDirection="column" gap={1}>
            <box flexDirection="column">
              <text fg={theme().text.base}>{abbrev(k.summary.total_tokens)} tokens</text>
              <text fg={theme().text.muted}>
                请求 {k.summary.request_count} · 缓存 {hitRate(k.summary.cache_hit_rate)}
              </text>
            </box>
            <box flexDirection="column">
              {creditRows.map((r) => (
                <box flexDirection="row" justifyContent="space-between">
                  <text fg={r.fg}>{r.left}</text>
                  {r.right ? <text fg={r.fg}>{r.right}</text> : null}
                </box>
              ))}
            </box>
            {top.length ? (
              <box flexDirection="column">
                {top.map((m) => {
                  const name = m.model.length > 14 ? m.model.slice(0, 13) + "…" : m.model
                  const share = m.share === null ? "--" : (m.share * 100).toFixed(0) + "%"
                  return (
                    <box flexDirection="row" justifyContent="space-between">
                      <text fg={theme().text.base}>{"· " + name}</text>
                      <text fg={theme().text.muted}>{share}</text>
                    </box>
                  )
                })}
              </box>
            ) : null}
            <text fg={theme().text.muted}>{timeOfDay(k.fetchedAt)} 更新</text>
          </box>
        )
      })()}
    </box>
  )
}

/** toast 节流:同级别告警 30 分钟内不重复 */
const TOAST_THROTTLE_MS = 30 * 60 * 1000
let lastToastAt = 0
let lastToastLevel = ""

/** 限额检查:今日/本周/本月 credit 任一超过阈值(80% 预警 / 100% 超限)时 toast 告警 */
async function quotaAlert(context: Plugin.Context) {
  const { ok, config } = resolveConfig(context.options as Record<string, unknown>)
  if (!ok) return
  try {
    const credits = await fetchCreditWindows(config)
    const stats = USAGE_WINDOWS.map((w) => {
      const limit = config[LIMIT_KEYS[w]]
      const credit = credits[w]
      return { w, credit, limit, pct: credit !== null && limit ? (credit / limit) * 100 : null }
    })
    const active = stats.filter((s) => s.pct !== null)
    if (!active.length) return
    const worst = active.reduce((a, b) => ((b.pct as number) > (a.pct as number) ? b : a))
    const pct = worst.pct as number
    if (pct < 80) return
    const label = worst.w === "today" ? "今日" : worst.w === "week" ? "本周" : "本月"
    const now = Date.now()
    const over = pct >= 100
    const level = over ? "over" : "near"
    if (now - lastToastAt < TOAST_THROTTLE_MS && lastToastLevel === level) return
    lastToastAt = now
    lastToastLevel = level
    context.ui.toast.show({
      title: over ? "蓝区火山用量告警" : "蓝区火山用量提醒",
      message: over
        ? `${label} Credit ${creditText(worst.credit)} 已超${label}限额 ${creditText(worst.limit)}(${pct.toFixed(0)}%)`
        : `${label} Credit ${creditText(worst.credit)} / ${label}限额 ${creditText(worst.limit)}(${pct.toFixed(0)}%)`,
      variant: over ? "error" : "warning",
    })
  } catch {
    /* 告警失败静默,不影响 opencode */
  }
}

export default Plugin.define({
  id: "opencode-bru-usage",
  setup(context) {
    // 侧栏 KPI 卡片
    const unregister = context.ui.slot({
      append: "sidebar.content",
      render: () => <BruUsageWidget options={context.options} />,
    })
    // session.idle → 限额 toast(节流 + 静默失败)
    const offIdle = context.data.on("session.idle", () => {
      void quotaAlert(context)
    })
    return () => {
      offIdle()
      unregister()
    }
  },
})