/**
 * BlueRegionUsage × opencode 插件共享层
 * 配置解析(共享 options / 环境变量 / 用户级文件)/ 网关 fetch 封装 / Credit 估算 / 格式化
 * server 与 tui 两个入口共用,保持无副作用、无 solid 依赖。
 */
import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
import { dirname } from "node:path"

export type UsageWindow = "today" | "week" | "month"

export interface BruConfig {
  baseUrl: string
  apiKey: string
  weeklyCreditLimit: number | null
  monthlyCreditLimit: number | null
  dailyCreditLimit: number | null
}

export class BruError extends Error {
  code: string
  status: number | null
  constructor(code: string, message: string, status: number | null = null) {
    super(message)
    this.code = code
    this.status = status
  }
}

const TIMEOUT_MS = 10_000

/** 蓝区火山网关(唯一部署了 usage ops API 的网关,内置为默认 baseUrl;options/env 可覆盖用于 mock 联调) */
export const DEFAULT_GATEWAY_BASE_URL = "https://st8tp3ajl0df3n8b8l8qu.apigateway-cn-beijing.volceapi.com"

function pick(...vals: unknown[]): unknown {
  for (const v of vals) {
    if (v !== undefined && v !== null && v !== "") return v
  }
  return undefined
}

function toLimit(v: unknown): number | null {
  if (v === undefined || v === null || v === "") return null
  const n = Number(v)
  return Number.isFinite(n) && n >= 0 ? n : null
}

// ---- 用户级配置文件(多用户个性化:每人一份 ~/.config/bru-usage/config.json)----

/**
 * 用户配置文件路径:$XDG_CONFIG_HOME/bru-usage/config.json(回退 ~/.config/...)。
 * 共享一台机器 / 一份共享配置时,每人只需写入自己的这份文件即可个性化 apiKey 与限额。
 */
export function bruUserConfigPath(): string {
  const env = (typeof process !== "undefined" && process.env) || {}
  const base = env.XDG_CONFIG_HOME || (env.HOME ? env.HOME + "/.config" : "")
  return base ? base + "/bru-usage/config.json" : ""
}

/** 读取用户配置(不存在 / 损坏时返回空对象,不抛错) */
export function readUserBruConfig(): Record<string, unknown> {
  try {
    const p = bruUserConfigPath()
    if (!p) return {}
    const parsed = JSON.parse(readFileSync(p, "utf8"))
    return parsed && typeof parsed === "object" ? parsed : {}
  } catch {
    return {}
  }
}

/** 合并写入用户配置(undefined 字段忽略;文件权限 0600),返回写入路径 */
export function writeUserBruConfig(patch: Record<string, unknown>): string {
  const p = bruUserConfigPath()
  if (!p) throw new BruError("no_home", "无法定位用户配置目录(HOME / XDG_CONFIG_HOME 未设置)")
  const next: Record<string, unknown> = { ...readUserBruConfig(), ...patch }
  for (const k of Object.keys(next)) {
    if (next[k] === undefined) delete next[k]
  }
  mkdirSync(dirname(p), { recursive: true })
  writeFileSync(p, JSON.stringify(next, null, 2) + "\n", { mode: 0o600 })
  return p
}

// ---- 从 opencode 配置识别身份(多人共用系统账户时:每人项目里的 provider key 即个人身份)----

/** 宽松解析 opencode.json / .jsonc(JSON 失败时剔除注释与字符串外的 // /*) */
function parseConfigFile(p: string): any | null {
  try {
    const txt = readFileSync(p, "utf8")
    try {
      return JSON.parse(txt)
    } catch {
      /* jsonc:手工剔除注释(跳过字符串字面量) */
      let out = ""
      let inStr = false
      let esc = false
      for (let i = 0; i < txt.length; i++) {
        const c = txt[i]
        if (inStr) {
          out += c
          if (esc) esc = false
          else if (c === "\\") esc = true
          else if (c === '"') inStr = false
          continue
        }
        if (c === '"') {
          inStr = true
          out += c
          continue
        }
        if (c === "/" && txt[i + 1] === "/") {
          while (i < txt.length && txt[i] !== "\n") i++
          out += "\n"
          continue
        }
        if (c === "/" && txt[i + 1] === "*") {
          i += 2
          while (i < txt.length && !(txt[i] === "*" && txt[i + 1] === "/")) i++
          i++
          continue
        }
        out += c
      }
      return JSON.parse(out)
    }
  } catch {
    return null
  }
}

function urlHost(u: string): string {
  try {
    return new URL(u).host
  } catch {
    return ""
  }
}

/**
 * 在项目(向上最多 8 级)与全局的 opencode 配置中,找 options.baseURL 与网关同源的 provider,
 * 返回其 apiKey —— 即 opencode 调模型实际使用的身份,用量归属天然一致。
 */
export function providerIdentityFor(gatewayBase: string): { apiKey: string; provider: string } | null {
  const gw = gatewayBase.replace(/\/+$/, "")
  const gwHost = urlHost(gw)
  if (!gw || !gwHost) return null
  const env = (typeof process !== "undefined" && process.env) || {}
  const cfgHome = env.XDG_CONFIG_HOME || (env.HOME ? env.HOME + "/.config" : "")
  const candidates: string[] = []
  let dir = (typeof process !== "undefined" && process.cwd()) || ""
  for (let i = 0; i < 8 && dir; i++) {
    candidates.push(
      dir + "/opencode.json",
      dir + "/opencode.jsonc",
      dir + "/.opencode/opencode.json",
      dir + "/.opencode/opencode.jsonc",
    )
    const parent = dirname(dir)
    if (parent === dir) break
    dir = parent
  }
  if (cfgHome) {
    candidates.push(cfgHome + "/opencode/opencode.json", cfgHome + "/opencode/opencode.jsonc")
  }
  for (const p of candidates) {
    const cfg = parseConfigFile(p)
    const providers = cfg && typeof cfg === "object" ? cfg.provider : null
    if (!providers || typeof providers !== "object") continue
    for (const [name, pv] of Object.entries<any>(providers)) {
      const baseURL = String(pv?.options?.baseURL || "").replace(/\/+$/, "")
      const apiKey = pv?.options?.apiKey
      if (!baseURL || typeof apiKey !== "string" || !apiKey) continue
      if (urlHost(baseURL) === gwHost || baseURL.startsWith(gw)) {
        return { apiKey, provider: name }
      }
    }
  }
  return null
}

/**
 * 解析插件配置。优先级:
 *   apiKey:用户配置文件 > 环境变量 > 项目/全局 opencode.json 的网关同源 provider key > plugin options
 *   限额:用户配置文件 > 环境变量 > plugin options
 *   baseUrl:plugin options > 环境变量 > 内置火山网关默认值(ops API 仅部署于该网关)
 * options 同时接受 baseUrl / gatewayBaseUrl 两种键名。
 * 未配置 Key 时 ok=false(调用方据此显示指引或直接跳过)。
 */
export function resolveConfig(options?: Record<string, unknown>): { ok: boolean; config: BruConfig; missing: string[] } {
  const env = (typeof process !== "undefined" && process.env) || {}
  const opts = options || {}
  const user = readUserBruConfig()
  const baseUrl = String(
    pick(opts.baseUrl, opts.gatewayBaseUrl, env.BRU_BASE_URL, env.BRU_GATEWAY_BASE_URL, DEFAULT_GATEWAY_BASE_URL) || "",
  ).replace(/\/+$/, "")
  const fromProvider = providerIdentityFor(baseUrl)
  const apiKey = String(pick(user.apiKey, env.BRU_API_KEY, fromProvider?.apiKey, opts.apiKey) || "")
  const config: BruConfig = {
    baseUrl,
    apiKey,
    dailyCreditLimit: toLimit(pick(user.dailyCreditLimit, env.BRU_DAILY_CREDIT_LIMIT, opts.dailyCreditLimit)),
    weeklyCreditLimit: toLimit(pick(user.weeklyCreditLimit, env.BRU_WEEKLY_CREDIT_LIMIT, opts.weeklyCreditLimit)),
    monthlyCreditLimit: toLimit(pick(user.monthlyCreditLimit, env.BRU_MONTHLY_CREDIT_LIMIT, opts.monthlyCreditLimit)),
  }
  const missing: string[] = []
  if (!baseUrl) missing.push("BRU_BASE_URL")
  if (!apiKey) missing.push("BRU_API_KEY")
  return { ok: missing.length === 0, config, missing }
}

/** 归一化错误信息(对齐 panel/js/api.js 语义) */
function normalizeError(err: unknown, status: number | null): BruError {
  if (err instanceof Error && err.name === "AbortError") {
    return new BruError("timeout", "请求超时(10 秒未响应)")
  }
  if (status === 401) return new BruError("unauthorized", "API Key 无效或已过期(401)")
  if (typeof status === "number") return new BruError("http", `网关返回错误(HTTP ${status})`, status)
  return new BruError("network", "网络失败:地址不可达")
}

/** GET 网关接口:Bearer 鉴权 + 10s 超时 + 错误归一化 */
export async function apiGet(cfg: BruConfig, path: string, params?: Record<string, string | number>): Promise<any> {
  let url: URL
  try {
    url = new URL(cfg.baseUrl + path)
    if (params) {
      for (const [k, v] of Object.entries(params)) {
        if (v !== undefined && v !== null) url.searchParams.set(k, String(v))
      }
    }
  } catch (e: any) {
    throw new BruError("bad_url", "网关地址非法:" + (e?.message || e))
  }
  const ctrl = new AbortController()
  const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS)
  let resp: Response
  try {
    resp = await fetch(url.toString(), {
      method: "GET",
      headers: { Authorization: "Bearer " + cfg.apiKey },
      signal: ctrl.signal,
    })
  } catch (err) {
    throw normalizeError(err, null)
  } finally {
    clearTimeout(timer)
  }
  const text = await resp.text().catch(() => "")
  let body: any = null
  try {
    body = text ? JSON.parse(text) : null
  } catch {
    /* 非 JSON */
  }
  if (!resp.ok) {
    const err = normalizeError(null, resp.status)
    if (body?.error?.message) err.message = String(body.error.message)
    throw err
  }
  if (body === null || typeof body !== "object") {
    throw new BruError("bad_response", "响应不是合法 JSON", resp.status)
  }
  return body
}

// ---- 数据形状(来自 functions/ops/vefaas_ops.py) ----

export interface SummaryData {
  req_tokens: number
  rsp_tokens: number
  total_tokens: number
  cached_tokens: number
  cache_hit_rate: number | null
  request_count: number
}

export interface ByModelRow {
  model: string
  req_tokens: number
  rsp_tokens: number
  cached_tokens: number
  total_tokens: number
  request_count: number
  share: number | null
  /** 服务端按新口径算好的窗口 Credit(分类 token × 目录价 × 厂商折扣);旧后端无此字段 */
  credit?: number | null
  credit_breakdown?: { input: number; cached: number; output: number } | null
  daily?: Array<{ date: string; req_tokens: number; rsp_tokens: number; total_tokens: number }>
}

export interface CreditHistoryEntry {
  from: string
  credit: number
}

export interface ModelCatalogEntry {
  id: string
  credit: number | null
  creditHistory: CreditHistoryEntry[]
}

/** 某天生效的系数:历史中最后一条 from <= 当天;无历史回退当前系数(对齐 panel creditOn) */
export function creditOn(entry: ModelCatalogEntry, dateStr: string | null): number | null {
  const hist = entry.creditHistory
  if (hist && hist.length && dateStr) {
    let v: number | null = null
    for (const e of hist) {
      if (e.from <= dateStr) v = e.credit
      else break
    }
    return v
  }
  return entry.credit
}

/** 单模型 Credit 估算:有 daily 按日分段,否则总量 × 当前系数(对齐 panel modelCreditUsage) */
export function modelCreditUsage(row: ByModelRow, catalog: Map<string, ModelCatalogEntry>): number | null {
  let sum = 0
  let has = false
  if (row.daily && row.daily.length) {
    for (const d of row.daily) {
      const entry = catalog.get(row.model)
      const c = entry ? creditOn(entry, d.date) : null
      if (c !== null) {
        has = true
        sum += ((d.total_tokens || 0) * c) / 1e6
      }
    }
    if (has) return sum
    return null
  }
  const entry = catalog.get(row.model)
  const c = entry ? creditOn(entry, null) : null
  return c !== null ? ((row.total_tokens || 0) * c) / 1e6 : null
}

export interface KpiSnapshot {
  window: UsageWindow
  consumer: string
  summary: SummaryData
  compare: SummaryData | null
  models: Array<{ model: string; totalTokens: number; share: number | null }>
  credit: number | null
  creditLimit: number | null
  fetchedAt: number
}

/** 三个统计窗口(today/week/month 通用顺序) */
export const USAGE_WINDOWS: UsageWindow[] = ["today", "week", "month"]

/**
 * 多窗口 Credit 概览:一次模型目录 + 三窗口 by-model 并发,
 * 供侧栏三行限额进度与 idle 限额告警使用。
 */
export async function fetchCreditWindows(cfg: BruConfig): Promise<Record<UsageWindow, number | null>> {
  const [catalog, ...byModels] = await Promise.all([
    fetchModelCatalog(cfg).catch(() => null),
    ...USAGE_WINDOWS.map((w) => apiGet(cfg, "/v1/usage/by-model", { window: w }).catch(() => null)),
  ])
  const out = { today: null, week: null, month: null } as Record<UsageWindow, number | null>
  USAGE_WINDOWS.forEach((w, i) => {
    const rows: ByModelRow[] = Array.isArray(byModels[i]?.data) ? byModels[i].data : []
    out[w] = creditFromRows(rows, catalog)
  })
  return out
}

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

/** /v1/models 目录:拉取并归一化 credit 系数(旧后端无 credit_history 时为空数组) */
export async function fetchModelCatalog(cfg: BruConfig): Promise<Map<string, ModelCatalogEntry>> {
  const out = new Map<string, ModelCatalogEntry>()
  const data = await apiGet(cfg, "/v1/models")
  for (const m of Array.isArray(data?.data) ? data.data : []) {
    if (!m || typeof m.id !== "string") continue
    const hist: CreditHistoryEntry[] = []
    if (Array.isArray(m.credit_history)) {
      for (const e of m.credit_history) {
        if (e && typeof e.from === "string" && typeof e.credit === "number") {
          hist.push({ from: e.from, credit: e.credit })
        }
      }
      hist.sort((a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : 0))
    }
    out.set(m.id, {
      id: m.id,
      credit: typeof m.credit === "number" ? m.credit : null,
      creditHistory: hist,
    })
  }
  return out
}

/** 由 summary / by-model / 目录组装 KPI 快照(fetchKpis 与 fetchKpiBundle 共用) */
function buildSnapshot(
  window: UsageWindow,
  summaryResp: any,
  rows: ByModelRow[],
  catalog: Map<string, ModelCatalogEntry> | null,
  cfg: BruConfig,
): KpiSnapshot {
  const summary: SummaryData = summaryResp?.data ?? {
    req_tokens: 0,
    rsp_tokens: 0,
    total_tokens: 0,
    cached_tokens: 0,
    cache_hit_rate: null,
    request_count: 0,
  }
  const compareRaw = summaryResp?.compare
  const compare: SummaryData | null = compareRaw
    ? {
        req_tokens: compareRaw.req_tokens ?? 0,
        rsp_tokens: compareRaw.rsp_tokens ?? 0,
        total_tokens: (compareRaw.req_tokens ?? 0) + (compareRaw.rsp_tokens ?? 0),
        cached_tokens: compareRaw.cached_tokens ?? 0,
        cache_hit_rate: null,
        request_count: compareRaw.request_count ?? 0,
      }
    : null
  const models = rows
    .map((r) => ({ model: r.model, totalTokens: r.total_tokens || 0, share: r.share }))
    .sort((a, b) => b.totalTokens - a.totalTokens)
  let credit: number | null = null
  if (catalog) {
    let sum = 0
    let has = false
    for (const r of rows) {
      const v = modelCreditUsage(r, catalog)
      if (v !== null) {
        has = true
        sum += v
      }
    }
    credit = has ? sum : null
  }
  return {
    window,
    consumer: String(summaryResp?.consumer || ""),
    summary,
    compare,
    models,
    credit,
    creditLimit: cfg[LIMIT_KEYS[window]] ?? null,
    fetchedAt: Date.now(),
  }
}

/**
 * 一次拉齐 KPI 所需数据:summary + by-model + models 并发。
 * models 失败时降级(credit 为 null),summary 失败则整体抛错。
 */
export async function fetchKpis(cfg: BruConfig, window: UsageWindow): Promise<KpiSnapshot> {
  const [summaryResp, byModelResp, catalog] = await Promise.all([
    apiGet(cfg, "/v1/usage/summary", { window }),
    apiGet(cfg, "/v1/usage/by-model", { window }).catch(() => null),
    fetchModelCatalog(cfg).catch(() => null),
  ])
  const rows: ByModelRow[] = Array.isArray(byModelResp?.data) ? byModelResp.data : []
  return buildSnapshot(window, summaryResp, rows, catalog, cfg)
}

/** 三窗口 Credit 汇总(给定各窗口 by-model 行与目录) */
function creditFromRows(rows: ByModelRow[], catalog: Map<string, ModelCatalogEntry> | null): number | null {
  // 新后端:行级 credit 直读(服务端分类计量口径,与面板 sumCredit 一致)
  let direct = 0
  let hasDirect = false
  for (const r of rows) {
    if (typeof r.credit === 'number') {
      hasDirect = true
      direct += r.credit
    }
  }
  if (hasDirect) return direct
  // 旧后端回退:目录系数 × daily 分段 / 总量(旧口径,逐日 total_tokens × 当日系数 ÷ 1e6)
  if (!catalog) return null
  let sum = 0
  let has = false
  for (const r of rows) {
    const v = modelCreditUsage(r, catalog)
    if (v !== null) {
      has = true
      sum += v
    }
  }
  return has ? sum : null
}

/**
 * 侧栏一次刷新所需全部数据:模型目录只拉一次(5 个请求,替代 fetchKpis+fetchCreditWindows 的 7 个)。
 * summary 失败整体抛错;by-model 单窗口失败降级为 null。
 */
export async function fetchKpiBundle(
  cfg: BruConfig,
): Promise<{ snap: KpiSnapshot; credits: Record<UsageWindow, number | null> }> {
  const [catalog, todaySummary, byToday, byWeek, byMonth] = await Promise.all([
    fetchModelCatalog(cfg).catch(() => null),
    apiGet(cfg, "/v1/usage/summary", { window: "today" }),
    apiGet(cfg, "/v1/usage/by-model", { window: "today" }).catch(() => null),
    apiGet(cfg, "/v1/usage/by-model", { window: "week" }).catch(() => null),
    apiGet(cfg, "/v1/usage/by-model", { window: "month" }).catch(() => null),
  ])
  const rowsOf = (r: any): ByModelRow[] => (Array.isArray(r?.data) ? r.data : [])
  return {
    snap: buildSnapshot("today", todaySummary, rowsOf(byToday), catalog, cfg),
    credits: {
      today: creditFromRows(rowsOf(byToday), catalog),
      week: creditFromRows(rowsOf(byWeek), catalog),
      month: creditFromRows(rowsOf(byMonth), catalog),
    },
  }
}

// ---- 格式化(对齐 panel/js/format.js 的 wan 风格) ----

/** 大数字缩写(国际单位):<1k 千分位;>=1k x.xK;>=1M x.xM;>=1B x.xxB(整 .0 省略) */
export function abbrev(n: number | null | undefined): string {
  if (n === null || n === undefined || !Number.isFinite(Number(n))) return "--"
  const v = Math.abs(Number(n))
  const neg = Number(n) < 0 ? "-" : ""
  if (v >= 1e9) return neg + (v / 1e9).toFixed(2).replace(/\.0$/, "") + "B"
  if (v >= 1e6) return neg + (v / 1e6).toFixed(1).replace(/\.0$/, "") + "M"
  if (v >= 1e3) return neg + (v / 1e3).toFixed(1).replace(/\.0$/, "") + "K"
  return neg + Number(n).toLocaleString("en-US")
}

/** Credit 用量:2 位小数千分位;0 < v < 0.01 显示 <0.01 */
export function creditText(v: number | null | undefined): string {
  if (v === null || v === undefined || !Number.isFinite(Number(v))) return "--"
  const n = Number(v)
  if (n > 0 && n < 0.01) return "<0.01"
  return n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

/** 命中率:0-1 比例 → 1 位小数百分比 */
export function hitRate(ratio: number | null | undefined): string {
  if (ratio === null || ratio === undefined || !Number.isFinite(Number(ratio))) return "--"
  return (Number(ratio) * 100).toFixed(1) + "%"
}

/** 文本进度条:█░,pct 为 0-100 */
export function bar(pct: number, width = 10): string {
  const p = Math.max(0, Math.min(100, pct))
  const filled = Math.round((p / 100) * width)
  return "█".repeat(filled) + "░".repeat(width - filled)
}

/** API Key 脱敏 */
export function maskKey(key: string): string {
  if (!key) return ""
  if (key.length <= 6) return key.charAt(0) + "••••"
  if (key.length <= 13) return key.slice(0, 4) + "••••" + key.slice(-2)
  return key.slice(0, 11) + "••••" + key.slice(-2)
}