import type { AssistantMessage } from "@saeeol/sdk/v2"
import type { TuiPlugin, TuiPluginApi, TuiPluginModule } from "@saeeol/plugin/tui"
import { createMemo } from "solid-js"
import { t } from "@/util/i18n"

const id = "internal:sidebar-context"

const money = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
})

function View(props: { api: TuiPluginApi; session_id: string }) {
  const theme = () => props.api.theme.current
  const msg = createMemo(() => props.api.state.session.messages(props.session_id))
  const cost = createMemo(() => msg().reduce((sum, item) => sum + (item.role === "assistant" ? item.cost : 0), 0))

  const state = createMemo(() => {
    const last = msg().findLast((item): item is AssistantMessage => item.role === "assistant" && item.tokens.output > 0)
    if (!last) {
      return {
        tokens: 0,
        percent: null,
      }
    }

    const tokens =
      last.tokens.input + last.tokens.output + last.tokens.reasoning + last.tokens.cache.read + last.tokens.cache.write
    const model = props.api.state.provider.find((item) => item.id === last.providerID)?.models?.[last.modelID]
    return {
      tokens,
      percent: model?.limit.context ? Math.round((tokens / model.limit.context) * 100) : null,
    }
  })

  return (
    <box>
      <text fg={theme().text}>
        <b>{t("sidebar.context.title")}</b>
      </text>
      <text fg={theme().textMuted}>{t("sidebar.context.tokens", { count: state().tokens.toLocaleString() })}</text>
      <text fg={theme().textMuted}>{t("sidebar.context.used", { percent: state().percent ?? 0 })}</text>
      <text fg={theme().textMuted}>{t("sidebar.context.spent", { cost: money.format(cost()) })}</text>
    </box>
  )
}

const tui: TuiPlugin = async (api) => {
  api.slots.register({
    order: 100,
    slots: {
      sidebar_content(_ctx, props) {
        return <View api={api} session_id={props.session_id} />
      },
    },
  })
}

const plugin: TuiPluginModule & { id: string } = {
  id,
  tui,
}

export default plugin
