Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

151 KB
Raw Blame
//! Token Plan / 编程套餐额度查询服务
//!
//! 支持 Kimi For Coding、智谱 GLM、MiniMax、ZenMux、火山方舟、OpenCode Go、Command Code、
//! Ollama Cloud、小米 MiMo Token Plan 的套餐额度查询。复用 subscription 模块的 SubscriptionQuota / QuotaTier 类型。

use super::subscription::{
    CredentialStatus, QuotaTier, SubscriptionQuota, TIER_CREDITS, TIER_FIVE_HOUR,
    TIER_KIMI_MONTHLY_CODE, TIER_KIMI_MONTHLY_TOTAL, TIER_MONTHLY, TIER_WEEKLY_LIMIT,
};
use super::usage_http::{parse_f64, send_for_json, JsonReply};
use crate::codex_config::codex_url_host_matches_any;
use std::time::{SystemTime, UNIX_EPOCH};

// ── 供应商检测 ──────────────────────────────────────────────

enum CodingPlanProvider {
    Kimi,
    ZhipuCn,
    ZhipuEn,
    MiniMaxCn,
    MiniMaxEn,
    ZenMux,
    /// 火山方舟 Agent Plan / Coding Plan(base_url 形如
    /// `https://ark.cn-beijing.volces.com/api/plan[/v3]`(Agent Plan)
    /// 或 `/api/coding[/v3]`(Coding Plan))。
    Volcengine,
    /// OpenCode Go($10/月订阅,美元额度三时间窗口)。base_url 分两个入口:
    /// `https://opencode.ai/inference/go/anthropic`(Anthropic 端,现行文档地址)
    /// 与 `https://opencode.ai/zen/go`(旧入口),OpenAI Chat 端在各自后面加 `/v1`。
    OpencodeGo,
    /// Command Code(Claude 使用 `/provider`,Codex 使用 `/provider/v1`)。
    CommandCode,
    /// Ollama Cloud(Claude 端 `https://ollama.com`,OpenAI 端 `https://ollama.com/v1`)。
    /// 本地 Ollama(localhost:11434)没有额度,不命中。
    OllamaCloud,
    /// 小米 MiMo Token Plan(`https://token-plan-cn.xiaomimimo.com/anthropic`、`/v1`)。
    /// 按量付费的 `api.xiaomimimo.com` 是另一套 Key,走余额查询,不在此命中。
    MimoTokenPlan,
}

fn detect_provider(base_url: &str) -> Option<CodingPlanProvider> {
    let host_is = |hosts: &[&str]| codex_url_host_matches_any(base_url, hosts);
    let path = url_path(base_url);
    let path_starts = |prefixes: &[&str]| prefixes.iter().any(|p| path.starts_with(p));
    if host_is(&["api.kimi.com", "api.kimi.ai"]) && path_starts(&["/coding"]) {
        Some(CodingPlanProvider::Kimi)
    } else if host_is(&["bigmodel.cn"]) {
        Some(CodingPlanProvider::ZhipuCn)
    } else if host_is(&["api.z.ai"]) {
        Some(CodingPlanProvider::ZhipuEn)
    } else if host_is(&["api.minimaxi.com", "api.minimax.cn"]) {
        Some(CodingPlanProvider::MiniMaxCn)
    } else if host_is(&["api.minimax.io"]) {
        Some(CodingPlanProvider::MiniMaxEn)
    } else if host_is(&["zenmux.ai"]) {
        Some(CodingPlanProvider::ZenMux)
    } else if host_is(&["opencode.ai"]) && path_starts(&["/zen/go", "/inference/go"]) {
        // 覆盖 /zen/go、/zen/go/v1 与 /inference/go、/inference/go/v1、
        // /inference/go/anthropic;Zen 按量版(/zen/v1 或 /inference/v1)
        // 没有任何用量/余额 API(实测 404),刻意不命中。
        Some(CodingPlanProvider::OpencodeGo)
    } else if host_is(&["api.commandcode.ai"])
        && (path == "/provider" || path.starts_with("/provider/"))
    {
        // 只有 /provider(Claude)与 /provider/v1(Codex)两个入口,不认 /providers。
        Some(CodingPlanProvider::CommandCode)
    } else if host_is(&["volces.com"]) && path_starts(&["/api/plan", "/api/coding"]) {
        // 仅匹配 Agent Plan(/api/plan[/v3])与 Coding Plan(/api/coding[/v3])
        // 入口;DouBaoSeed 按量付费走 /api/v3 与 /api/compatible,没有套餐
        // 额度,不在此命中。用量探测本身是双 plan 自动探测(GetAFPUsage →
        // GetCodingPlanUsage),无需在此区分两种订阅。
        Some(CodingPlanProvider::Volcengine)
    } else if host_is(&["ollama.com"]) {
        Some(CodingPlanProvider::OllamaCloud)
    } else if host_is(&["token-plan-cn.xiaomimimo.com"]) {
        Some(CodingPlanProvider::MimoTokenPlan)
    } else {
        None
    }
}

/// `base_url` 的路径部分(小写,不含查询串和片段),没有 scheme 也能取。
fn url_path(base_url: &str) -> String {
    let url = base_url.trim().to_ascii_lowercase();
    let rest = crate::codex_config::url_after_scheme(&url);
    let path = rest.find(['/', '?', '#']).map_or("", |i| &rest[i..]);
    path.split(['?', '#']).next().unwrap_or("").to_string()
}

/// 按地址认出的套餐 id,取值与前端 `CodingPlanProviderEntry.id` 一致
/// (写进 `usage_script.coding_plan_provider`,用量弹窗下拉按它回显)。
/// 智谱团队版与个人版地址相同、无法自动区分,这里永远返回个人版。
pub(crate) fn detect_provider_id(base_url: &str) -> Option<&'static str> {
    Some(match detect_provider(base_url)? {
        CodingPlanProvider::Kimi => "kimi",
        CodingPlanProvider::ZhipuCn | CodingPlanProvider::ZhipuEn => "zhipu",
        CodingPlanProvider::MiniMaxCn | CodingPlanProvider::MiniMaxEn => "minimax",
        CodingPlanProvider::ZenMux => "zenmux",
        CodingPlanProvider::Volcengine => "volcengine",
        CodingPlanProvider::OpencodeGo => "opencode_go",
        CodingPlanProvider::CommandCode => "command_code",
        CodingPlanProvider::OllamaCloud => "ollama_cloud",
        CodingPlanProvider::MimoTokenPlan => "mimo",
    })
}

fn now_millis() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as i64
}

fn millis_to_iso8601(ms: i64) -> Option<String> {
    let secs = ms / 1000;
    let nsecs = ((ms % 1000) * 1_000_000) as u32;
    chrono::DateTime::from_timestamp(secs, nsecs).map(|dt| dt.to_rfc3339())
}

/// 从 JSON 值提取重置时间,兼容字符串和数字格式
/// - 字符串:直接返回(ISO 8601)
/// - 数字:自动判断秒/毫秒并转为 ISO 8601
fn extract_reset_time(value: &serde_json::Value) -> Option<String> {
    if let Some(s) = value.as_str() {
        return Some(s.to_string());
    }
    if let Some(n) = value.as_i64() {
        // 0/负时间戳(如火山 session 无活跃窗口回 -1)视为无重置时间
        if n <= 0 {
            return None;
        }
        // 区分秒和毫秒:秒级时间戳 < 1e12,毫秒 >= 1e12
        let ms = if n < 1_000_000_000_000 { n * 1000 } else { n };
        return millis_to_iso8601(ms);
    }
    None
}

fn make_error(msg: String) -> SubscriptionQuota {
    SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: None,
        success: false,
        tiers: vec![],
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: Some(msg),
        queried_at: Some(now_millis()),
    }
}

/// 凭据被拒(401/403):标记为过期,错误文案带上状态码。
fn auth_error(status: reqwest::StatusCode) -> SubscriptionQuota {
    expired_key_error(format!("Authentication failed (HTTP {status})"))
}

fn expired_key_error(error: String) -> SubscriptionQuota {
    SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Expired,
        credential_message: Some("Invalid API key".to_string()),
        success: false,
        tiers: vec![],
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: Some(error),
        queried_at: Some(now_millis()),
    }
}

/// 套餐查询的结果。智谱个人版账户没有 Coding Plan(按量付费)时单独返回
/// `ZhipuNoPlan`(内含原来的失败结果),用量查询入口据此改查账户余额
/// (`commands::provider` 的 token_plan 分支);不回落的调用方用 [`Self::into_quota`]。
pub(crate) enum CodingPlanOutcome {
    Quota(SubscriptionQuota),
    ZhipuNoPlan(SubscriptionQuota),
}

impl CodingPlanOutcome {
    pub(crate) fn into_quota(self) -> SubscriptionQuota {
        match self {
            Self::Quota(quota) | Self::ZhipuNoPlan(quota) => quota,
        }
    }
}

// ── Kimi For Coding ─────────────────────────────────────────

/// Resolve the Kimi quota API root from the user's configured `base_url`.
///
/// Kimi For Coding 分国内站与海外站(「Kimi For Coding Global」,www.kimi.ai +
/// api.kimi.ai),两套账号体系互不鉴权:拿海外 Key 查国内端点(或反过来)只会
/// 得到 401,所以额度查询必须跟着 provider 所在区域走。Coding 数据面的 API 根
/// 在两个区域都固定是 `{host}/coding/v1`——像 Claude Code 的
/// `ANTHROPIC_BASE_URL=https://api.kimi.ai/coding/` 这类不带 `/v1` 的写法,
/// 直接拼 `/usages` 会 404(实测两端点均如此),这里统一归一到带 `/v1` 的根。
fn kimi_quota_base(base_url: &str) -> &'static str {
    if codex_url_host_matches_any(base_url, &["api.kimi.ai"]) {
        "https://api.kimi.ai/coding/v1"
    } else {
        "https://api.kimi.com/coding/v1"
    }
}

async fn query_kimi(base_url: &str, api_key: &str) -> Result<SubscriptionQuota, String> {
    query_kimi_at(kimi_quota_base(base_url), api_key).await
}

/// `base_url` is the Kimi Code API root (`https://api.kimi.ai/coding/v1` for
/// global accounts); `token` is an API key or an official OAuth access token.
pub(crate) async fn query_kimi_at(
    base_url: &str,
    token: &str,
) -> Result<SubscriptionQuota, String> {
    let client = crate::proxy::http_client::get();
    let api_key = token;

    let request = client
        .get(format!("{}/usages", base_url.trim_end_matches('/')))
        .header("Authorization", format!("Bearer {api_key}"))
        .header("Accept", "application/json")
        .timeout(std::time::Duration::from_secs(15));
    let body = match send_for_json(request).await? {
        JsonReply::Body(body) => body,
        JsonReply::Denied(status) => return Ok(auth_error(status)),
        JsonReply::Failed(message) => return Ok(make_error(message)),
    };

    let mut tiers = Vec::new();

    // 5 小时窗口限额(优先显示)
    if let Some(limits) = body.get("limits").and_then(|v| v.as_array()) {
        for limit_item in limits {
            if let Some(detail) = limit_item.get("detail") {
                let limit = detail.get("limit").and_then(parse_f64).unwrap_or(1.0);
                let remaining = detail.get("remaining").and_then(parse_f64).unwrap_or(0.0);
                let resets_at = detail.get("resetTime").and_then(extract_reset_time);

                let used = (limit - remaining).max(0.0);
                let utilization = if limit > 0.0 {
                    (used / limit) * 100.0
                } else {
                    0.0
                };
                tiers.push(QuotaTier {
                    name: "five_hour".to_string(),
                    utilization,
                    resets_at,
                    used_value_usd: None,
                    max_value_usd: None,
                });
            }
        }
    }

    // 总体用量(周限额)
    if let Some(usage) = body.get("usage") {
        let limit = usage.get("limit").and_then(parse_f64).unwrap_or(1.0);
        let remaining = usage.get("remaining").and_then(parse_f64).unwrap_or(0.0);
        let resets_at = usage.get("resetTime").and_then(extract_reset_time);

        let used = (limit - remaining).max(0.0);
        let utilization = if limit > 0.0 {
            (used / limit) * 100.0
        } else {
            0.0
        };
        tiers.push(QuotaTier {
            name: "weekly_limit".to_string(),
            utilization,
            resets_at,
            used_value_usd: None,
            max_value_usd: None,
        });
    }

    // 新套餐只有 usages 比例字段,月总额度与月编程额度是两个独立的桶。
    // 旧计数字段存在时保留其结果(部分旧套餐的 ratio 曾返回 0),只补缺失的档位。
    if let Some(usages) = body.get("usages") {
        for (field, name) in [
            ("limit_5h", TIER_FIVE_HOUR),
            ("limit_7d", TIER_WEEKLY_LIMIT),
            ("limit_month_total", TIER_KIMI_MONTHLY_TOTAL),
            ("limit_month_code", TIER_KIMI_MONTHLY_CODE),
        ] {
            if tiers.iter().any(|tier| tier.name == name) {
                continue;
            }
            let Some(entry) = usages.get(field) else {
                continue;
            };
            let Some(utilization) = entry
                .get("used_ratio")
                .and_then(parse_f64)
                .map(|ratio| ratio * 100.0)
                .filter(|value| value.is_finite() && *value >= 0.0)
            else {
                continue;
            };
            tiers.push(QuotaTier {
                name: name.to_string(),
                utilization,
                resets_at: entry.get("reset_time").and_then(extract_reset_time),
                used_value_usd: None,
                max_value_usd: None,
            });
        }
    }

    Ok(SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: None,
        success: true,
        tiers,
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(now_millis()),
    })
}

// ── 智谱 GLM ────────────────────────────────────────────────

/// 智谱 TOKENS_LIMIT 条目按 `unit` 字段的显式窗口分类。
enum ZhipuWindow {
    FiveHour,
    Weekly,
}

/// 按 `unit` 字段判定 TOKENS_LIMIT 条目所属窗口。
///
/// 实测形态(bigmodel.cn 与 z.ai 共用同一后端,字段一致):
/// - `unit: 3, number: 5` → 5 小时滚动窗口(老/新套餐均有)
/// - `unit: 6, number: 7` 与 `unit: 6, number: 1` → 每周窗口(两种取值都被
///   实测过,故只锚定 `unit`、不绑 `number`)
///
/// `unit` 缺失或值不认识时返回 None,由调用方走重置时间启发式兜底。
fn classify_zhipu_window(item: &serde_json::Value) -> Option<ZhipuWindow> {
    match item.get("unit").and_then(|v| v.as_i64()) {
        Some(3) => Some(ZhipuWindow::FiveHour),
        Some(6) => Some(ZhipuWindow::Weekly),
        _ => None,
    }
}

/// 把智谱 `data` 里的 `limits[]` 解析成 tier 列表。
///
/// 分类优先级:
/// 1. 显式字段:`unit` 标识窗口类型(见 [`classify_zhipu_window`])。不能按
///    `nextResetTime` 排序代替——周期末尾每周窗口会比 5 小时窗口更早重置
///    (issue #3036),时间排序在该场景必然把两桶标反。
/// 2. 兜底启发式(`unit` 缺失或不识别):无 `nextResetTime` 的条目优先归
///    five_hour(5 小时桶在 0% 等状态下可能没有 reset),其余按 reset 升序
///    依次填入仍空缺的槽位。
///
/// 老套餐(2026-02-12 前订阅)只回 1 条
/// `TOKENS_LIMIT`,自然降级为仅展示 `five_hour`;新套餐回 2 条。
fn parse_zhipu_token_tiers(data: &serde_json::Value) -> Vec<QuotaTier> {
    type Entry = (Option<i64>, f64, Option<String>);
    let mut five_hour: Option<Entry> = None;
    let mut weekly: Option<Entry> = None;
    let mut unclassified: Vec<Entry> = Vec::new();

    if let Some(limits) = data.get("limits").and_then(|v| v.as_array()) {
        for limit_item in limits {
            let limit_type = limit_item
                .get("type")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            // 大小写不敏感比较:上游若把 "TOKENS_LIMIT" 改成小写或驼峰,依然能识别
            if !(limit_type.eq_ignore_ascii_case("TOKENS_LIMIT")
                || limit_type.eq_ignore_ascii_case("CREDIT_LIMIT"))
            {
                continue;
            }
            let percentage = limit_item
                .get("percentage")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0);
            let reset_ms = limit_item.get("nextResetTime").and_then(|v| v.as_i64());
            let reset_iso = reset_ms.and_then(millis_to_iso8601);
            let entry = (reset_ms, percentage, reset_iso);
            match classify_zhipu_window(limit_item) {
                Some(ZhipuWindow::FiveHour) if five_hour.is_none() => five_hour = Some(entry),
                Some(ZhipuWindow::Weekly) if weekly.is_none() => weekly = Some(entry),
                _ => unclassified.push(entry),
            }
        }
    }

    unclassified.sort_by_key(|(reset, _, _)| (reset.is_some(), reset.unwrap_or(i64::MIN)));
    for entry in unclassified {
        if five_hour.is_none() {
            five_hour = Some(entry);
        } else if weekly.is_none() {
            weekly = Some(entry);
        }
        // 智谱当前最多两条 TOKENS_LIMIT,多余的忽略
    }

    let mut tiers = Vec::new();
    for (name, slot) in [(TIER_FIVE_HOUR, five_hour), (TIER_WEEKLY_LIMIT, weekly)] {
        if let Some((_, percentage, resets_at)) = slot {
            tiers.push(QuotaTier {
                name: name.to_string(),
                utilization: percentage,
                resets_at,
                used_value_usd: None,
                max_value_usd: None,
            });
        }
    }
    tiers
}

/// Resolve the Zhipu quota endpoint from the user's configured `base_url`.
///
/// Zhipu ships as two distinct presets (Zhipu GLM = `open.bigmodel.cn`,
/// Zhipu GLM en = `api.z.ai`) that share the same quota path and JSON shape.
/// The quota endpoint lives on the same host as the user's coding endpoint,
/// so we route by `base_url` and let the caller's existing reachability
/// (they're already using this host to run coding) determine success — no
/// cross-host fallback, no auth-error heuristics.
fn zhipu_quota_base(base_url: &str) -> &'static str {
    if codex_url_host_matches_any(base_url, &["bigmodel.cn"]) {
        "https://open.bigmodel.cn"
    } else {
        "https://api.z.ai"
    }
}

async fn query_zhipu(base_url: &str, api_key: &str) -> Result<CodingPlanOutcome, String> {
    let url = format!(
        "{}/api/monitor/usage/quota/limit",
        zhipu_quota_base(base_url)
    );
    query_zhipu_at(&url, api_key).await
}

/// 拆出 url 参数便于用本地 server 测试鉴权失败 / 没有套餐两条路径。
async fn query_zhipu_at(url: &str, api_key: &str) -> Result<CodingPlanOutcome, String> {
    let client = crate::proxy::http_client::get();
    let request = client
        .get(url)
        .header("Authorization", api_key) // 注意:智谱不加 Bearer 前缀
        .header("Content-Type", "application/json")
        .header("Accept-Language", "en-US,en")
        .timeout(std::time::Duration::from_secs(15));
    let body = match send_for_json(request).await? {
        JsonReply::Body(body) => body,
        JsonReply::Denied(status) => return Ok(CodingPlanOutcome::Quota(auth_error(status))),
        JsonReply::Failed(message) => return Ok(CodingPlanOutcome::Quota(make_error(message))),
    };

    Ok(zhipu_outcome_from_body(&body))
}

/// 智谱个人版:账户没有 Coding Plan(按量付费)单独认出来,交给调用方改查余额。
fn zhipu_outcome_from_body(body: &serde_json::Value) -> CodingPlanOutcome {
    let quota = zhipu_quota_from_body(body);
    if zhipu_body_has_no_plan(body) {
        CodingPlanOutcome::ZhipuNoPlan(quota)
    } else {
        CodingPlanOutcome::Quota(quota)
    }
}

/// 按量账户查套餐时,接口回 HTTP 200 + 业务错误(2026-10-18 国内站实测):
/// `{"code":500,"msg":"当前用户不存在coding plan","success":false}`。
/// 只认「msg 提到 coding plan 且说没有」,Key 无效(HTTP 401/403)、网络错误、
/// 其他业务错误都不算,免得把真故障显示成余额。英文站文案未实测,关键词放宽了几个说法。
fn zhipu_body_has_no_plan(body: &serde_json::Value) -> bool {
    if body.get("success").and_then(|v| v.as_bool()) != Some(false) {
        return false;
    }
    let msg = body
        .get("msg")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_lowercase();
    let compact: String = msg
        .chars()
        .filter(|c| !c.is_whitespace() && *c != '_' && *c != '-')
        .collect();
    compact.contains("codingplan")
        && [
            "不存在",
            "没有",
            "未开通",
            "not exist",
            "not found",
            "not have",
            "doesn't have",
            "no coding plan",
            "not subscribed",
        ]
        .iter()
        .any(|kw| msg.contains(kw))
}

/// 解析智谱额度响应体(个人版与团队版共用同一 shape)。
/// 仅在 HTTP 成功、body 已完整读取并解析为 JSON 后调用——本函数不做任何网络 IO,
/// 故无瞬时失败通道,确定性失败直接落进 `Ok(success:false)`。
fn zhipu_quota_from_body(body: &serde_json::Value) -> SubscriptionQuota {
    // 检查业务级别错误
    if body.get("success").and_then(|v| v.as_bool()) == Some(false) {
        let msg = body
            .get("msg")
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown error");
        return make_error(format!("API error: {msg}"));
    }

    let data = match body.get("data") {
        Some(d) => d,
        None => return make_error("Missing 'data' field in response".to_string()),
    };

    let tiers = parse_zhipu_token_tiers(data);

    // 套餐等级存入 credential_message
    let level = data
        .get("level")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: level,
        success: true,
        tiers,
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(now_millis()),
    }
}

// ── MiniMax ─────────────────────────────────────────────────

async fn query_minimax(api_key: &str, is_cn: bool) -> Result<SubscriptionQuota, String> {
    let client = crate::proxy::http_client::get();

    // 额度接口只在 api.minimaxi.com / api.minimax.io 有公开出处;国内新推理域名
    // api.minimax.cn 未见该接口文档,沿用旧域名(同一账号体系与 Key)
    let api_domain = if is_cn {
        "api.minimaxi.com"
    } else {
        "api.minimax.io"
    };
    let url = format!("https://{api_domain}/v1/api/openplatform/coding_plan/remains");

    let request = client
        .get(&url)
        .header("Authorization", format!("Bearer {api_key}"))
        .header("Content-Type", "application/json")
        .timeout(std::time::Duration::from_secs(15));
    let body = match send_for_json(request).await? {
        JsonReply::Body(body) => body,
        JsonReply::Denied(status) => return Ok(auth_error(status)),
        JsonReply::Failed(message) => return Ok(make_error(message)),
    };

    // 检查业务级别错误
    if let Some(base_resp) = body.get("base_resp") {
        let status_code = base_resp
            .get("status_code")
            .and_then(|v| v.as_i64())
            .unwrap_or(-1);
        if status_code != 0 {
            let msg = base_resp
                .get("status_msg")
                .and_then(|v| v.as_str())
                .unwrap_or("Unknown error");
            return Ok(make_error(format!("API error (code {status_code}): {msg}")));
        }
    }

    // 提取纯函数便于无 mock 单元测试;新接口直接给"剩余百分比",反转为已用百分比
    let tiers = parse_minimax_tiers(&body);

    Ok(SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: None,
        success: true,
        tiers,
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(now_millis()),
    })
}

// ── ZenMux ──────────────────────────────────────────────────

async fn query_zenmux(base_url: &str, api_key: &str) -> Result<SubscriptionQuota, String> {
    let client = crate::proxy::http_client::get();

    let request = client
        .get(base_url)
        .header("Authorization", format!("Bearer {api_key}"))
        .header("Accept", "application/json")
        .timeout(std::time::Duration::from_secs(15));
    let body = match send_for_json(request).await? {
        JsonReply::Body(body) => body,
        JsonReply::Denied(status) => return Ok(auth_error(status)),
        JsonReply::Failed(message) => return Ok(make_error(message)),
    };

    // 检查业务级别错误
    if body.get("success").and_then(|v| v.as_bool()) != Some(true) {
        let msg = body
            .get("message")
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown error");
        return Ok(make_error(format!("API error: {msg}")));
    }

    let data = match body.get("data") {
        Some(d) => d,
        None => return Ok(make_error("Missing 'data' field in response".to_string())),
    };

    let mut tiers = Vec::new();

    // 5 小时窗口限额
    if let Some(q5h) = data.get("quota_5_hour") {
        let usage_pct = q5h
            .get("usage_percentage")
            .and_then(parse_f64)
            .unwrap_or(0.0);
        let resets_at = q5h
            .get("resets_at")
            .and_then(|v| v.as_str())
            .map(String::from);
        let used_usd = q5h.get("used_value_usd").and_then(parse_f64);
        let max_usd = q5h.get("max_value_usd").and_then(parse_f64);
        tiers.push(QuotaTier {
            name: "five_hour".to_string(),
            utilization: usage_pct * 100.0,
            resets_at,
            used_value_usd: used_usd,
            max_value_usd: max_usd,
        });
    }

    // 7 天窗口限额
    if let Some(q7d) = data.get("quota_7_day") {
        let usage_pct = q7d
            .get("usage_percentage")
            .and_then(parse_f64)
            .unwrap_or(0.0);
        let resets_at = q7d
            .get("resets_at")
            .and_then(|v| v.as_str())
            .map(String::from);
        let used_usd = q7d.get("used_value_usd").and_then(parse_f64);
        let max_usd = q7d.get("max_value_usd").and_then(parse_f64);
        tiers.push(QuotaTier {
            name: "weekly_limit".to_string(),
            utilization: usage_pct * 100.0,
            resets_at,
            used_value_usd: used_usd,
            max_value_usd: max_usd,
        });
    }

    // 套餐等级和账户状态存入 credential_message
    let plan_tier = data
        .get("plan")
        .and_then(|p| p.get("tier"))
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let account_status = data
        .get("account_status")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let plan_info = if !plan_tier.is_empty() {
        format!("{plan_tier} ({account_status})")
    } else {
        String::new()
    };

    Ok(SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: if plan_info.is_empty() {
            None
        } else {
            Some(plan_info)
        },
        success: true,
        tiers,
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(now_millis()),
    })
}

/// 从 `/coding_plan/remains` 响应中解析 MiniMax 编程套餐的额度 tier。
///
/// 新接口语义:`current_*_remaining_percent` 是"剩余百分比"(0-100),
/// `model_remains` 数组里有 `general`(编程套餐)和 `video` 等其他模型,
/// 这里只取 `general`,跳过 video。
///
/// 5h 桶始终存在;周桶并非所有套餐都有,靠 `current_weekly_status` 区分:
/// 1 = 正常计时,2 = 周额度已耗尽(照常展示),3 = 无周限额
/// (该字段为 3 时 `remaining_percent` 恒为 100,不应展示)。
fn parse_minimax_tiers(body: &serde_json::Value) -> Vec<QuotaTier> {
    let mut tiers = Vec::new();

    let Some(model_remains) = body.get("model_remains").and_then(|v| v.as_array()) else {
        return tiers;
    };

    // 只取 model_name == "general" 的条目,跳过 video 等非编程模型
    let Some(item) = model_remains.iter().find(|item| {
        item.get("model_name")
            .and_then(|v| v.as_str())
            .map(|s| s == "general")
            .unwrap_or(false)
    }) else {
        return tiers;
    };

    // 5h 桶:剩余百分比 → 已用百分比
    if let Some(remain_pct) = item
        .get("current_interval_remaining_percent")
        .and_then(|v| v.as_f64())
    {
        let resets_at = item
            .get("end_time")
            .and_then(|v| v.as_i64())
            .and_then(millis_to_iso8601);
        tiers.push(QuotaTier {
            name: TIER_FIVE_HOUR.to_string(),
            utilization: 100.0 - remain_pct,
            resets_at,
            used_value_usd: None,
            max_value_usd: None,
        });
    }

    // 周桶:status=1 正常计时;status=2 表示周额度已耗尽(剩余 0%,官方控制台仍
    // 显示该桶并按周限额限流),照常展示成「已用完」;status=3 表示该套餐无周
    // 限额(remaining_percent 恒为 100),跳过
    let weekly_status = item.get("current_weekly_status").and_then(|v| v.as_i64());
    if weekly_status == Some(1) || weekly_status == Some(2) {
        if let Some(remain_pct) = item
            .get("current_weekly_remaining_percent")
            .and_then(|v| v.as_f64())
        {
            let resets_at = item
                .get("weekly_end_time")
                .and_then(|v| v.as_i64())
                .and_then(millis_to_iso8601);
            tiers.push(QuotaTier {
                name: TIER_WEEKLY_LIMIT.to_string(),
                utilization: 100.0 - remain_pct,
                resets_at,
                used_value_usd: None,
                max_value_usd: None,
            });
        }
    }

    tiers
}

// ── OpenCode Go ─────────────────────────────────────────────

/// 解析 OpenCode Go usage 端点响应为 tier 列表。
///
/// 响应形态(上游 `packages/console/app/src/routes/zen/go/v1/usage.ts`):
/// `{"usage":{"rolling"|"weekly"|"monthly":{"status":"ok"|"rate-limited",
/// "percent":0-100 已用整数,"resetsAt":ISO8601}}}`,三窗口对应文档口径
/// $12/5h、$30/周、$60/月(端点不回传金额,仅百分比)。
///
/// 该端点是第一方但未文档化的路由,上线当天(2026-08-11)就改过一次形态
/// (旧扁平 `rollingUsage/usagePercent/resetInSec` 已作废),故逐窗口防御
/// 解析:缺失或 percent 不可解析的窗口跳过,不整体失败。
///
/// `status=="rate-limited"` 时上游已把 percent 钉在 100,无需特判;
/// percent 为 0 时上游的 `resetsAt` 是「now+窗口时长」的占位值(滚动窗按
/// 最后记账时间整窗清零,此时窗口早已过期),丢弃不展示倒计时。
fn parse_opencode_go_tiers(body: &serde_json::Value) -> Vec<QuotaTier> {
    const WINDOWS: [(&str, &str); 3] = [
        ("rolling", TIER_FIVE_HOUR),
        ("weekly", TIER_WEEKLY_LIMIT),
        ("monthly", TIER_MONTHLY),
    ];
    let Some(usage) = body.get("usage") else {
        return Vec::new();
    };
    let mut tiers = Vec::new();
    for (key, tier_name) in WINDOWS {
        let Some(window) = usage.get(key) else {
            continue;
        };
        let Some(percent) = window.get("percent").and_then(parse_f64) else {
            continue;
        };
        let resets_at = if percent > 0.0 {
            window.get("resetsAt").and_then(extract_reset_time)
        } else {
            None
        };
        tiers.push(QuotaTier {
            name: tier_name.to_string(),
            utilization: percent,
            resets_at,
            used_value_usd: None,
            max_value_usd: None,
        });
    }
    tiers
}

async fn query_opencode_go(api_key: &str) -> Result<SubscriptionQuota, String> {
    let client = crate::proxy::http_client::get();

    // 用量端点只认 `Authorization: Bearer`——与推理侧 /messages 只认
    // x-api-key 正好相反,不能互换。
    let request = client
        .get("https://opencode.ai/zen/go/v1/usage")
        .header("Authorization", format!("Bearer {api_key}"))
        .header("Accept", "application/json")
        .timeout(std::time::Duration::from_secs(15));
    let body = match send_for_json(request).await? {
        JsonReply::Body(body) => body,
        JsonReply::Denied(reqwest::StatusCode::FORBIDDEN) => {
            return Ok(make_error(
                "API key is valid but has no OpenCode Go subscription (HTTP 403)".to_string(),
            ))
        }
        JsonReply::Denied(status) => return Ok(auth_error(status)),
        JsonReply::Failed(message) => return Ok(make_error(message)),
    };

    let tiers = parse_opencode_go_tiers(&body);
    // 三个窗口一个都没解析出来 = 响应形态不认识(未文档化端点可能再次
    // 变形),明确报错而不是渲染一张空卡片。
    if tiers.is_empty() {
        return Ok(make_error("Unexpected usage response shape".to_string()));
    }

    Ok(SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: None,
        success: true,
        tiers,
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(now_millis()),
    })
}

// ── Ollama Cloud ─────────────────────────────────────────────

/// 解析 `GET https://ollama.com/api/balance`(docs.ollama.com/api/balance)。
///
/// 现行套餐:`included.balance_usd`(本期剩余)/ `included.allowance_usd`(本期总额),
/// 本期截止 `included.period.until`,折成一档月度百分比。旧套餐 `included` 下是
/// `session` / `weekly` 两档,各带 `remaining_percent`(0–100)与 `resets_at`。
/// `purchased.balance_usd`(另购余额)不进额度档:卡片的余额行只认 Codex Credits。
fn parse_ollama_cloud_tiers(body: &serde_json::Value) -> Vec<QuotaTier> {
    let Some(included) = body.get("included") else {
        return Vec::new();
    };
    let balance = included.get("balance_usd").and_then(parse_f64);
    let allowance = included.get("allowance_usd").and_then(parse_f64);
    if let (Some(balance), Some(allowance)) = (balance, allowance) {
        if allowance > 0.0 {
            let used = (allowance - balance).clamp(0.0, allowance);
            return vec![QuotaTier {
                name: TIER_MONTHLY.to_string(),
                utilization: used / allowance * 100.0,
                resets_at: included
                    .get("period")
                    .and_then(|period| period.get("until"))
                    .and_then(extract_reset_time),
                used_value_usd: None,
                max_value_usd: None,
            }];
        }
    }

    let mut tiers = Vec::new();
    for (key, tier_name) in [("session", TIER_FIVE_HOUR), ("weekly", TIER_WEEKLY_LIMIT)] {
        let Some(window) = included.get(key) else {
            continue;
        };
        let Some(remaining) = window.get("remaining_percent").and_then(parse_f64) else {
            continue;
        };
        tiers.push(QuotaTier {
            name: tier_name.to_string(),
            utilization: (100.0 - remaining).clamp(0.0, 100.0),
            resets_at: window.get("resets_at").and_then(extract_reset_time),
            used_value_usd: None,
            max_value_usd: None,
        });
    }
    tiers
}

async fn query_ollama_cloud(api_key: &str) -> Result<SubscriptionQuota, String> {
    let client = crate::proxy::http_client::get();
    let request = client
        .get("https://ollama.com/api/balance")
        .header("Authorization", format!("Bearer {api_key}"))
        .header("Accept", "application/json")
        .timeout(std::time::Duration::from_secs(15));
    let body = match send_for_json(request).await? {
        JsonReply::Body(body) => body,
        JsonReply::Denied(reqwest::StatusCode::FORBIDDEN) => {
            return Ok(make_error(
                "Ollama account is suspended (HTTP 403)".to_string(),
            ))
        }
        JsonReply::Denied(status) => return Ok(auth_error(status)),
        JsonReply::Failed(message) => return Ok(make_error(message)),
    };

    let tiers = parse_ollama_cloud_tiers(&body);
    if tiers.is_empty() {
        // 按量付费账户 allowance_usd 为 0,没有套餐额度可显示
        let no_plan = body
            .get("included")
            .and_then(|included| included.get("allowance_usd"))
            .and_then(parse_f64)
            .is_some_and(|allowance| allowance <= 0.0);
        return Ok(make_error(if no_plan {
            "No included Ollama Cloud credits on this account (pay-as-you-go)".to_string()
        } else {
            "Unexpected balance response shape".to_string()
        }));
    }

    Ok(SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: None,
        success: true,
        tiers,
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(now_millis()),
    })
}

// ── 小米 MiMo Token Plan ─────────────────────────────────────

/// MiMo 的周期时间是「UTC,`YYYY-MM-DD HH:mm:ss`」(无 `T`、无时区),WebKit 的
/// `Date` 不认这种写法,这里转成 RFC 3339;已经是别的格式时照原样交给通用解析。
fn mimo_period_time(value: &serde_json::Value) -> Option<String> {
    if let Some(text) = value.as_str() {
        if let Ok(naive) = chrono::NaiveDateTime::parse_from_str(text.trim(), "%Y-%m-%d %H:%M:%S") {
            return Some(naive.and_utc().to_rfc3339());
        }
    }
    extract_reset_time(value)
}

/// 解析 `GET /v1/platform/token_plan`(mimo.mi.com/docs/zh-CN/api/asset/credits-get)。
///
/// `quota.total_credits`(本期总额,含补偿积分)/ `used_credits` / `remaining_credits`
/// 折成一档用量百分比,本期截止 `period.end_at` 作重置时间。套餐有月付也有年付,
/// 周期长短不固定,所以用通用的「额度」档,不冒充「每月」。
fn parse_mimo_token_plan_tiers(body: &serde_json::Value) -> Vec<QuotaTier> {
    let Some(quota) = body.get("quota") else {
        return Vec::new();
    };
    let Some(total) = quota.get("total_credits").and_then(parse_f64) else {
        return Vec::new();
    };
    if !total.is_finite() || total <= 0.0 {
        return Vec::new();
    }
    let used = match quota.get("used_credits").and_then(parse_f64) {
        Some(used) => used,
        None => match quota.get("remaining_credits").and_then(parse_f64) {
            Some(remaining) => total - remaining,
            None => return Vec::new(),
        },
    };
    vec![QuotaTier {
        name: TIER_CREDITS.to_string(),
        utilization: (used / total * 100.0).clamp(0.0, 100.0),
        resets_at: body
            .get("period")
            .and_then(|period| period.get("end_at"))
            .and_then(mimo_period_time),
        used_value_usd: None,
        max_value_usd: None,
    }]
}

async fn query_mimo_token_plan(api_key: &str) -> Result<SubscriptionQuota, String> {
    let client = crate::proxy::http_client::get();
    let request = client
        .get("https://token-plan-cn.xiaomimimo.com/v1/platform/token_plan")
        .header("Authorization", format!("Bearer {api_key}"))
        .header("Accept", "application/json")
        .timeout(std::time::Duration::from_secs(15));
    let body = match send_for_json(request).await? {
        JsonReply::Body(body) => body,
        // 401:Key 无效,或把按量付费的 sk- Key 用在了 Token Plan 上
        JsonReply::Denied(reqwest::StatusCode::UNAUTHORIZED) => {
            return Ok(expired_key_error(
                "Authentication failed (HTTP 401): use the Token Plan API key (tp-...)"
                    .to_string(),
            ))
        }
        // 403:地区不支持或 Key 被风控,官方建议换一个新 Key
        JsonReply::Denied(status) => {
            return Ok(expired_key_error(format!(
                "MiMo rejected this API key: region not supported or blocked by risk control (HTTP {status})"
            )))
        }
        JsonReply::Failed(message) => return Ok(make_error(message)),
    };

    let tiers = parse_mimo_token_plan_tiers(&body);
    if tiers.is_empty() {
        return Ok(make_error(
            "No Token Plan credits on this account".to_string(),
        ));
    }

    Ok(SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: None,
        success: true,
        tiers,
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(now_millis()),
    })
}

// ── Command Code ─────────────────────────────────────────────

/// Command Code 的 `/alpha` 控制面接口固定在根域名;推理数据面才使用
/// `/provider` / `/provider/v1`。不要复用 provider 的 base_url。
const COMMAND_CODE_API_BASE: &str = "https://api.commandcode.ai";

enum CommandCodeFetch {
    Body(serde_json::Value),
    AuthExpired,
    Error(String),
}

fn command_code_url(base_url: &str, path: &str, params: &[(&str, &str)]) -> Result<String, String> {
    let mut url = url::Url::parse(&format!("{}{}", base_url.trim_end_matches('/'), path))
        .map_err(|e| format!("Invalid Command Code endpoint: {e}"))?;
    if !params.is_empty() {
        let mut query = url.query_pairs_mut();
        for (key, value) in params {
            query.append_pair(key, value);
        }
    }
    Ok(url.into())
}

/// `/alpha` 是官方 CLI 使用的私有路由,未公开文档化;保持宽松解析。
async fn fetch_command_code_json(
    client: &reqwest::Client,
    base_url: &str,
    path: &str,
    params: &[(&str, &str)],
    api_key: &str,
) -> Result<CommandCodeFetch, String> {
    let url = command_code_url(base_url, path, params)?;
    let response = client
        .get(url)
        .header("Authorization", format!("Bearer {api_key}"))
        .header("Accept", "application/json")
        .timeout(std::time::Duration::from_secs(15))
        .send()
        .await
        .map_err(|e| format!("Network error: {e}"))?;

    let status = response.status();
    if status == reqwest::StatusCode::UNAUTHORIZED {
        return Ok(CommandCodeFetch::AuthExpired);
    }

    let raw = response
        .bytes()
        .await
        .map_err(|e| format!("Failed to read response: {e}"))?;
    if !status.is_success() {
        let body = String::from_utf8_lossy(&raw);
        return Ok(CommandCodeFetch::Error(format!(
            "API error (HTTP {status}): {body}"
        )));
    }

    match serde_json::from_slice(&raw) {
        Ok(body) => Ok(CommandCodeFetch::Body(body)),
        Err(e) => Ok(CommandCodeFetch::Error(format!(
            "Failed to parse response: {e}"
        ))),
    }
}

fn command_code_window_tier(window: Option<&serde_json::Value>, name: &str) -> Option<QuotaTier> {
    let window = window?;
    let used = window.get("used").and_then(parse_f64)?;
    let cap = window.get("cap").and_then(parse_f64)?;
    if cap <= 0.0 {
        return None;
    }
    Some(QuotaTier {
        name: name.to_string(),
        utilization: used / cap * 100.0,
        resets_at: window.get("resetAt").and_then(extract_reset_time),
        used_value_usd: None,
        max_value_usd: None,
    })
}

fn parse_command_code_quota(
    credits_response: &serde_json::Value,
    subscription_response: Option<&serde_json::Value>,
    summary_response: &serde_json::Value,
) -> SubscriptionQuota {
    let Some(credit_root) = credits_response.get("credits") else {
        return make_error("Missing 'credits' field in response".to_string());
    };
    let credit_values = credit_root;

    // Command Code 的 monthly tier 是套餐级月度额度;purchased/free credits
    // 只参与月度百分比计算,不参与 5h/weekly rolling window。与 OpenCode Go
    // 一致,frontend 只展示三类窗口的百分比和重置倒计时。
    let monthly_remaining = credit_values
        .get("monthlyCredits")
        .and_then(parse_f64)
        .unwrap_or(0.0)
        .max(0.0);
    let purchased_remaining = credit_values
        .get("purchasedCredits")
        .and_then(parse_f64)
        .unwrap_or(0.0)
        .max(0.0);
    let free_remaining = credit_values
        .get("freeCredits")
        .and_then(parse_f64)
        .unwrap_or(0.0)
        .max(0.0);
    let total_remaining = monthly_remaining + purchased_remaining + free_remaining;
    let Some(total_spent) = summary_response.get("totalCost").and_then(parse_f64) else {
        return make_error("Missing 'totalCost' field in response".to_string());
    };
    let total_spent = total_spent.max(0.0);
    let total_pool = total_spent + total_remaining;

    let subscription = subscription_response.and_then(|body| body.get("data"));
    let period_end = subscription
        .and_then(|data| data.get("currentPeriodEnd"))
        .and_then(extract_reset_time);
    let plan_id = subscription
        .and_then(|data| data.get("planId"))
        .and_then(|value| value.as_str())
        .or_else(|| credit_root.get("planId").and_then(|value| value.as_str()))
        .map(str::to_string);

    let mut tiers = Vec::new();
    // 实际 credits 响应把 windowLimits 放在 credits 同级;保留嵌套位置兼容
    // 已出现过的响应变体。
    if let Some(window_limits) = credits_response
        .get("windowLimits")
        .or_else(|| credit_root.get("windowLimits"))
    {
        if window_limits
            .get("limited")
            .and_then(|value| value.as_bool())
            .unwrap_or(false)
        {
            if let Some(tier) =
                command_code_window_tier(window_limits.get("fiveHour"), TIER_FIVE_HOUR)
            {
                tiers.push(tier);
            }
            if let Some(tier) =
                command_code_window_tier(window_limits.get("weekly"), TIER_WEEKLY_LIMIT)
            {
                tiers.push(tier);
            }
        }
    }

    tiers.push(QuotaTier {
        name: TIER_MONTHLY.to_string(),
        utilization: if total_pool > 0.0 {
            total_spent / total_pool * 100.0
        } else {
            0.0
        },
        resets_at: period_end,
        used_value_usd: None,
        max_value_usd: None,
    });

    SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: plan_id,
        success: true,
        tiers,
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(now_millis()),
    }
}

async fn query_command_code_at(base_url: &str, api_key: &str) -> Result<SubscriptionQuota, String> {
    let client = crate::proxy::http_client::get();

    let whoami = match fetch_command_code_json(
        &client,
        base_url,
        "/alpha/whoami",
        &[("limits", "1")],
        api_key,
    )
    .await?
    {
        CommandCodeFetch::Body(body) => body,
        CommandCodeFetch::AuthExpired => return Ok(auth_error(reqwest::StatusCode::UNAUTHORIZED)),
        CommandCodeFetch::Error(error) => return Ok(make_error(error)),
    };

    let org_id = whoami
        .get("org")
        .and_then(|org| org.get("id"))
        .and_then(|id| id.as_str())
        .map(str::to_string);
    let org_params: Vec<(&str, &str)> = org_id
        .as_deref()
        .map(|id| vec![("orgId", id)])
        .unwrap_or_default();

    let credits = match fetch_command_code_json(
        &client,
        base_url,
        "/alpha/billing/credits",
        &org_params,
        api_key,
    )
    .await?
    {
        CommandCodeFetch::Body(body) => body,
        CommandCodeFetch::AuthExpired => return Ok(auth_error(reqwest::StatusCode::UNAUTHORIZED)),
        CommandCodeFetch::Error(error) => return Ok(make_error(error)),
    };

    let subscription = match fetch_command_code_json(
        &client,
        base_url,
        "/alpha/billing/subscriptions",
        &org_params,
        api_key,
    )
    .await?
    {
        CommandCodeFetch::Body(body) => Some(body),
        CommandCodeFetch::AuthExpired => return Ok(auth_error(reqwest::StatusCode::UNAUTHORIZED)),
        CommandCodeFetch::Error(error) => return Ok(make_error(error)),
    };

    let period_start = subscription
        .as_ref()
        .and_then(|body| body.get("data"))
        .and_then(|data| data.get("currentPeriodStart"))
        .and_then(|value| value.as_str())
        .map(str::to_string);
    let mut summary_params: Vec<(&str, &str)> = Vec::new();
    if let Some(period_start) = period_start.as_deref() {
        summary_params.push(("since", period_start));
    }
    if let Some(org_id) = org_id.as_deref() {
        summary_params.push(("orgId", org_id));
    }
    let summary = match fetch_command_code_json(
        &client,
        base_url,
        "/alpha/usage/summary",
        &summary_params,
        api_key,
    )
    .await?
    {
        CommandCodeFetch::Body(body) => body,
        CommandCodeFetch::AuthExpired => return Ok(auth_error(reqwest::StatusCode::UNAUTHORIZED)),
        CommandCodeFetch::Error(error) => return Ok(make_error(error)),
    };

    Ok(parse_command_code_quota(
        &credits,
        subscription.as_ref(),
        &summary,
    ))
}

async fn query_command_code(api_key: &str) -> Result<SubscriptionQuota, String> {
    query_command_code_at(COMMAND_CODE_API_BASE, api_key).await
}

// ── 火山方舟 Agent Plan / Coding Plan ───────────────────────
//
// 与 Kimi/MiniMax(数据面 Bearer 余额接口)不同,火山用量接口是**控制面
// OpenAPI**:统一网关 `open.volcengineapi.com`(**不是**数据面推理域名
// `ark.cn-beijing.volces.com`),形如
// `POST https://open.volcengineapi.com/?Action=...&Version=2024-01-01&Region=cn-beijing`,
// **强制火山引擎签名 V4(AK/SK)**——实测复用推理 Bearer Key 会被网关以
// `400 InvalidAuthorization` 拒绝(格式层拒绝,非权限问题)。因此用户需在用量查询
// 里另填火山账号的 AccessKey ID + Secret(与推理 Key 是两套凭据)。两个 plan 用
// 同一份 AK/SK,故鉴权类错误直接停、不再试另一个 plan。
//
// 自动探测:先调 `GetAFPUsage`(Agent Plan,回绝对额度 Quota/Used),未订阅再调
// `GetCodingPlanUsage`(Coding Plan,回百分比)。

/// 控制面 OpenAPI 统一网关(区别于数据面推理域名 ark.cn-beijing.volces.com)。
const VOLCENGINE_OPENAPI_HOST: &str = "open.volcengineapi.com";
const VOLCENGINE_API_VERSION: &str = "2024-01-01";
/// ark 控制面 OpenAPI 的默认 Region(Agent/Coding Plan 目前在 cn-beijing)。
const VOLCENGINE_DEFAULT_REGION: &str = "cn-beijing";

/// 单次 OpenAPI 调用的归类结果。
enum VolcCall {
    /// 2xx 且 JSON 可解析、无 OpenAPI 级错误(业务 Result 仍可能为空=未订阅)。
    Body(serde_json::Value),
    /// 硬鉴权失败(HTTP 401/403 或 AccessDenied/Signature 等错误码)——两个 plan
    /// 共用凭据,命中即停。
    Auth(String),
    /// 非鉴权 HTTP 错误 / 响应体非法 JSON——记录后可继续尝试另一个 plan。
    Soft(String),
    /// 瞬时传输失败(网络/超时/读体中断)——同 host 的另一个 plan 大概率同样
    /// 失败,调用方应立即以 `Err` 传播(前端 reject → retry + 保留上次成功值)。
    Transient(String),
}

/// 从数据面 base_url 提取控制面 OpenAPI 所需的 Region(如
/// `ark.cn-beijing.volces.com` → `cn-beijing`);无法识别时回落 cn-beijing。
/// 控制面 Host 是固定网关(`VOLCENGINE_OPENAPI_HOST`),不随 base_url 变化。
fn volcengine_region(base_url: &str) -> String {
    crate::codex_config::codex_url_host(base_url)
        .split('.')
        .find(|p| p.starts_with("cn-") || p.starts_with("ap-"))
        .map(|p| p.to_string())
        .unwrap_or_else(|| VOLCENGINE_DEFAULT_REGION.to_string())
}

/// 判断 OpenAPI 错误码是否属于鉴权类(需要硬停并提示换 AK/SK)。
fn volcengine_is_auth_error_code(code: &str) -> bool {
    let c = code.to_lowercase();
    c.contains("auth")
        || c.contains("signature")
        || c.contains("accessdenied")
        || c.contains("denied")
        || c.contains("unauthorized")
        || c.contains("forbidden")
        || c.contains("credential")
        || c.contains("token")
}

/// 提取火山 OpenAPI 响应里的 `ResponseMetadata.Error`(或顶层 `Error`)。
fn volcengine_response_error(body: &serde_json::Value) -> Option<(String, String)> {
    let err = body
        .get("ResponseMetadata")
        .and_then(|m| m.get("Error"))
        .or_else(|| body.get("Error"))?;
    let code = err
        .get("Code")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let msg = err
        .get("Message")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    if code.is_empty() && msg.is_empty() {
        None
    } else {
        Some((code, msg))
    }
}

/// 鉴权失败时的引导文案,附加在错误后。
const VOLCENGINE_AKSK_HINT: &str =
    "Check the AccessKey ID / Secret are correct and the account has Ark usage-query (OpenAPI) permission.";

// ── 火山引擎签名 V4(AK/SK)─────────────────────────────────
//
// 算法是 AWS SigV4 的火山变体(对照官方 volc-openapi-demos/signature/java/Sign.java)。
// **两处致命差异,照搬 s3.rs 的标准 SigV4 会签名失败**:
//   1. canonical headers 与 SignedHeaders 用**固定顺序**
//      `host;x-date;x-content-sha256;content-type`(**不按字母序**,s3.rs 是字母序);
//   2. algorithm 串 `HMAC-SHA256`(无 `AWS4` 前缀)、credential scope 结尾 `request`
//      (非 `aws4_request`)、签名密钥 `kDate=HMAC(SK, date)`(SK 不加 `AWS4` 前缀)。
// canonical query 仍按 key 字母序(与标准 SigV4 一致);service=`ark`、POST、空 body。

const VOLCENGINE_SERVICE: &str = "ark";
const VOLCENGINE_CONTENT_TYPE: &str = "application/json; charset=utf-8";
const VOLCENGINE_SIGNED_HEADERS: &str = "host;x-date;x-content-sha256;content-type";

fn volc_hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
    use hmac::{Hmac, Mac};
    type HmacSha256 = Hmac<sha2::Sha256>;
    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts any key length");
    mac.update(data);
    mac.finalize().into_bytes().to_vec()
}

fn volc_sha256_hex(data: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    format!("{:x}", Sha256::digest(data))
}

/// RFC3986 unreserved 之外全部按 `%XX` 编码(用于 canonical query string)。
fn volc_uri_encode(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for byte in input.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char)
            }
            _ => {
                use std::fmt::Write;
                let _ = write!(out, "%{byte:02X}");
            }
        }
    }
    out
}

/// 构造按 key 字母序排序、逐段 URL 编码的 canonical query string。
/// 同一份字符串既用于签名也用于实际请求 URL,保证两者完全一致。
fn volcengine_canonical_query(action: &str, region: &str) -> String {
    let mut pairs = [
        ("Action", action),
        ("Region", region),
        ("Version", VOLCENGINE_API_VERSION),
    ];
    pairs.sort_by(|a, b| a.0.cmp(b.0));
    pairs
        .iter()
        .map(|(k, v)| format!("{}={}", volc_uri_encode(k), volc_uri_encode(v)))
        .collect::<Vec<_>>()
        .join("&")
}

/// 生成火山引擎签名 V4 的鉴权头,返回 `(Authorization, X-Date, X-Content-Sha256)`,
/// 三者都要塞进请求头;`canonical_query` 必须与实际请求 URL 的 query 完全一致。
/// `now` 作参数传入便于写确定性单测。
fn volcengine_sign(
    access_key_id: &str,
    secret_access_key: &str,
    region: &str,
    canonical_query: &str,
    body: &[u8],
    now: chrono::DateTime<chrono::Utc>,
) -> (String, String, String) {
    let x_date = now.format("%Y%m%dT%H%M%SZ").to_string();
    let short_date = now.format("%Y%m%d").to_string();
    let x_content_sha256 = volc_sha256_hex(body);

    // 固定顺序 canonical headers(火山特有,**不排序**)。
    let canonical_headers = format!(
        "host:{VOLCENGINE_OPENAPI_HOST}\nx-date:{x_date}\nx-content-sha256:{x_content_sha256}\ncontent-type:{VOLCENGINE_CONTENT_TYPE}\n"
    );
    let canonical_request = format!(
        "POST\n/\n{canonical_query}\n{canonical_headers}\n{VOLCENGINE_SIGNED_HEADERS}\n{x_content_sha256}"
    );

    let credential_scope = format!("{short_date}/{region}/{VOLCENGINE_SERVICE}/request");
    let string_to_sign = format!(
        "HMAC-SHA256\n{x_date}\n{credential_scope}\n{}",
        volc_sha256_hex(canonical_request.as_bytes())
    );

    // 签名密钥派生:kDate=HMAC(SK, date)(SK **不加** AWS4 前缀),终止串 `request`。
    let k_date = volc_hmac_sha256(secret_access_key.as_bytes(), short_date.as_bytes());
    let k_region = volc_hmac_sha256(&k_date, region.as_bytes());
    let k_service = volc_hmac_sha256(&k_region, VOLCENGINE_SERVICE.as_bytes());
    let k_signing = volc_hmac_sha256(&k_service, b"request");
    let signature: String = volc_hmac_sha256(&k_signing, string_to_sign.as_bytes())
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect();

    let authorization = format!(
        "HMAC-SHA256 Credential={access_key_id}/{credential_scope}, SignedHeaders={VOLCENGINE_SIGNED_HEADERS}, Signature={signature}"
    );
    (authorization, x_date, x_content_sha256)
}

async fn volcengine_openapi_call(
    region: &str,
    access_key_id: &str,
    secret_access_key: &str,
    action: &str,
) -> VolcCall {
    let client = crate::proxy::http_client::get();
    // canonical query 同时用于签名与实际 URL,确保两者逐字一致(否则签名不匹配)。
    let canonical_query = volcengine_canonical_query(action, region);
    let url = format!("https://{VOLCENGINE_OPENAPI_HOST}/?{canonical_query}");
    let body: &[u8] = b"";
    let (authorization, x_date, x_content_sha256) = volcengine_sign(
        access_key_id,
        secret_access_key,
        region,
        &canonical_query,
        body,
        chrono::Utc::now(),
    );

    let resp = client
        .post(&url)
        .header("X-Date", x_date)
        .header("X-Content-Sha256", x_content_sha256)
        .header("Content-Type", VOLCENGINE_CONTENT_TYPE)
        .header("Authorization", authorization)
        .body(body.to_vec())
        .timeout(std::time::Duration::from_secs(15))
        .send()
        .await;

    let resp = match resp {
        Ok(r) => r,
        Err(e) => return VolcCall::Transient(format!("Network error: {e}")),
    };

    let status = resp.status();
    if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
        return VolcCall::Auth(format!(
            "Authentication failed (HTTP {status}). {VOLCENGINE_AKSK_HINT}"
        ));
    }
    if !status.is_success() {
        // 火山 OpenAPI 网关对签名/凭据类错误常返 4xx(多为 HTTP 400)并携带与 200
        // 路径相同的 ResponseMetadata.Error 信封,而非 401/403。这里也解析信封,让
        // Bearer 被拒时仍能给出 AK/SK 引导并标记凭据失效,而不是当成普通 API 错误。
        let raw = resp.text().await.unwrap_or_default();
        if let Ok(body) = serde_json::from_str::<serde_json::Value>(&raw) {
            if let Some((code, msg)) = volcengine_response_error(&body) {
                if volcengine_is_auth_error_code(&code) {
                    return VolcCall::Auth(format!(
                        "Authentication failed (HTTP {status}, {code}): {msg}. {VOLCENGINE_AKSK_HINT}"
                    ));
                }
                return VolcCall::Soft(format!("API error (HTTP {status}, {code}): {msg}"));
            }
        }
        return VolcCall::Soft(format!("API error (HTTP {status}): {raw}"));
    }

    // 同 Bearer 路径:先 bytes() 再解析——读体失败是瞬时(Transient),解析失败
    // 是确定性(Soft)。reqwest 的 json() 把读体错误也包成 decode,无法区分。
    let raw = match resp.bytes().await {
        Ok(b) => b,
        Err(e) => return VolcCall::Transient(format!("Failed to read response: {e}")),
    };
    let body: serde_json::Value = match serde_json::from_slice(&raw) {
        Ok(v) => v,
        Err(e) => return VolcCall::Soft(format!("Failed to parse response: {e}")),
    };

    // 火山 OpenAPI 业务错误常以 200 + ResponseMetadata.Error 返回。
    if let Some((code, msg)) = volcengine_response_error(&body) {
        if volcengine_is_auth_error_code(&code) {
            return VolcCall::Auth(format!(
                "Authentication failed ({code}): {msg}. {VOLCENGINE_AKSK_HINT}"
            ));
        }
        return VolcCall::Soft(format!("API error ({code}): {msg}"));
    }

    VolcCall::Body(body)
}

/// 解析 `GetAFPUsage` 的 `Result` 为 tier 列表。
///
/// 展示 5h / 周 / 月三个窗口(与控制台一致);`AFPDaily` 被官方控制台隐藏
/// (其 Quota 常高于周上限,属历史默认值而非强制限额),故跳过。
/// `Quota`/`Used` 是绝对 AFP 值,已用百分比 = Used/Quota×100;`Quota<=0` 视为
/// 该窗口未订阅/未启用,跳过——也用于把"已鉴权但无 Agent Plan"识别为空结果,
/// 从而回落到 Coding Plan 探测。
fn parse_afp_tiers(result: &serde_json::Value) -> Vec<QuotaTier> {
    let mut tiers = Vec::new();
    for (key, name) in [
        ("AFPFiveHour", TIER_FIVE_HOUR),
        ("AFPWeekly", TIER_WEEKLY_LIMIT),
        ("AFPMonthly", TIER_MONTHLY),
    ] {
        let Some(win) = result.get(key) else { continue };
        let quota = win.get("Quota").and_then(parse_f64).unwrap_or(0.0);
        if quota <= 0.0 {
            continue;
        }
        let used = win.get("Used").and_then(parse_f64).unwrap_or(0.0);
        // 已用百分比;不做范围裁剪,与 parse_zhipu_token_tiers/parse_minimax_tiers
        // 的约定一致(下游渲染层负责显示策略)。
        let utilization = used / quota * 100.0;
        let resets_at = win.get("ResetTime").and_then(extract_reset_time);
        tiers.push(QuotaTier {
            name: name.to_string(),
            utilization,
            resets_at,
            used_value_usd: None,
            max_value_usd: None,
        });
    }
    tiers
}

/// 把 `GetCodingPlanUsage` 的 window 标签归一到 tier 名。
fn volcengine_coding_window(label: &str) -> Option<&'static str> {
    match label.to_lowercase().as_str() {
        "session" | "5h" | "fivehour" | "five_hour" | "rolling_5h" => Some(TIER_FIVE_HOUR),
        "weekly" | "week" | "7d" => Some(TIER_WEEKLY_LIMIT),
        "monthly" | "month" => Some(TIER_MONTHLY),
        _ => None,
    }
}

/// 解析 `GetCodingPlanUsage` 的 `Result` 为 tier 列表(防御式)。
///
/// 该接口官方文档未给出逐字段规格,依据官方 ark-cli 描述:回 session/weekly/
/// monthly 窗口、**只给百分比**(已用)、重置时间是秒级。这里宽松匹配
/// `QuotaUsage`/`Usages`/`Details` 数组及多种字段名,命中即用、未命中跳过。
fn parse_coding_plan_tiers(result: &serde_json::Value) -> Vec<QuotaTier> {
    let mut tiers = Vec::new();
    let arr = result
        .get("QuotaUsage")
        .and_then(|v| v.as_array())
        .or_else(|| result.get("Usages").and_then(|v| v.as_array()))
        .or_else(|| result.get("Details").and_then(|v| v.as_array()));
    let Some(arr) = arr else { return tiers };

    for item in arr {
        // 真实字段是 `Level`(实测 2026-06-21:session/weekly/monthly);其余作防御式 fallback。
        let label = item
            .get("Level")
            .and_then(|v| v.as_str())
            .or_else(|| item.get("Type").and_then(|v| v.as_str()))
            .or_else(|| item.get("Period").and_then(|v| v.as_str()))
            .or_else(|| item.get("Label").and_then(|v| v.as_str()))
            .or_else(|| item.get("Window").and_then(|v| v.as_str()))
            .unwrap_or("");
        let Some(name) = volcengine_coding_window(label) else {
            continue;
        };
        let utilization = item
            .get("Percent")
            .and_then(parse_f64)
            .or_else(|| item.get("UsedPercent").and_then(parse_f64))
            .or_else(|| item.get("UsagePercent").and_then(parse_f64))
            .unwrap_or(0.0);
        // 兼容秒/毫秒/字符串(extract_reset_time 内部已区分秒与毫秒)。
        let resets_at = item
            .get("ResetTime")
            .or_else(|| item.get("ResetTimestamp"))
            .and_then(extract_reset_time);
        tiers.push(QuotaTier {
            name: name.to_string(),
            utilization,
            resets_at,
            used_value_usd: None,
            max_value_usd: None,
        });
    }
    tiers
}

fn volcengine_success(tiers: Vec<QuotaTier>, plan: Option<String>) -> SubscriptionQuota {
    SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: plan,
        success: true,
        tiers,
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(now_millis()),
    }
}

async fn query_volcengine(
    base_url: &str,
    access_key_id: &str,
    secret_access_key: &str,
) -> Result<SubscriptionQuota, String> {
    let region = volcengine_region(base_url);
    let mut soft_errors: Vec<String> = Vec::new();
    // 2xx + 无 Error 信封但解析不出额度时,截断原始响应用于诊断(区分"真没订阅"
    // 与"字段名/包裹层猜错")。签名若不通会走 Auth/Soft 分支,到不了这里。
    let mut empty_responses: Vec<String> = Vec::new();
    let summarize = |action: &str, body: &serde_json::Value| -> String {
        let raw: String = body.to_string().chars().take(700).collect();
        format!("{action}={raw}")
    };

    // 1) Agent Plan:GetAFPUsage
    match volcengine_openapi_call(&region, access_key_id, secret_access_key, "GetAFPUsage").await {
        VolcCall::Auth(detail) => return Ok(expired_key_error(detail)),
        VolcCall::Transient(detail) => return Err(format!("GetAFPUsage: {detail}")),
        VolcCall::Soft(detail) => soft_errors.push(format!("GetAFPUsage: {detail}")),
        VolcCall::Body(body) => {
            let result = body.get("Result").unwrap_or(&body);
            let tiers = parse_afp_tiers(result);
            if !tiers.is_empty() {
                let plan = result
                    .get("PlanType")
                    .and_then(|v| v.as_str())
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(|s| format!("Agent Plan {s}"));
                return Ok(volcengine_success(tiers, plan));
            }
            empty_responses.push(summarize("GetAFPUsage", &body));
        }
    }

    // 2) Coding Plan:GetCodingPlanUsage
    match volcengine_openapi_call(
        &region,
        access_key_id,
        secret_access_key,
        "GetCodingPlanUsage",
    )
    .await
    {
        VolcCall::Auth(detail) => return Ok(expired_key_error(detail)),
        VolcCall::Transient(detail) => return Err(format!("GetCodingPlanUsage: {detail}")),
        VolcCall::Soft(detail) => soft_errors.push(format!("GetCodingPlanUsage: {detail}")),
        VolcCall::Body(body) => {
            let result = body.get("Result").unwrap_or(&body);
            let tiers = parse_coding_plan_tiers(result);
            if !tiers.is_empty() {
                return Ok(volcengine_success(tiers, Some("Coding Plan".to_string())));
            }
            empty_responses.push(summarize("GetCodingPlanUsage", &body));
        }
    }

    if !soft_errors.is_empty() {
        Ok(make_error(soft_errors.join("; ")))
    } else if !empty_responses.is_empty() {
        // 签名已通过、请求到达业务层,但响应里没有可解析的额度。带上原始响应,
        // 便于核对真实字段名/包裹层,或确认确实未订阅。
        Ok(make_error(format!(
            "No active subscription found (signature OK). Raw: {}",
            empty_responses.join(" || ")
        )))
    } else {
        Ok(make_error(
            "No active Agent Plan or Coding Plan subscription found for this credential"
                .to_string(),
        ))
    }
}

// ── 公开入口 ────────────────────────────────────────────────

/// 构造"凭据缺失 / 域名未命中"的失败结果(NotFound 状态 + 明确错误文案)。
fn coding_plan_not_found(error: &str) -> SubscriptionQuota {
    SubscriptionQuota {
        tool: "coding_plan".to_string(),
        credential_status: CredentialStatus::NotFound,
        credential_message: None,
        success: false,
        tiers: vec![],
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: Some(error.to_string()),
        queried_at: None,
    }
}

// ── 智谱团队套餐(Team Plan)──────────────────────────────────
//
// 与个人版的差异仅在请求构造(参考 token-monitor/src/shared/zaiTeamLimits.js):
// - 固定走国内站 open.bigmodel.cn(团队版仅存在于国内站,z.ai 国际站无 team 档)
// - 同一 quota 路径加 `?type=2`
// - 额外请求头 bigmodel-organization / bigmodel-project(两者 + api_key 缺一不可)
// 响应 shape 与个人版完全一致 → 复用 zhipu_quota_from_body / parse_zhipu_token_tiers。
const ZHIPU_TEAM_QUOTA_URL: &str = "https://open.bigmodel.cn/api/monitor/usage/quota/limit";

async fn query_zhipu_team(
    api_key: &str,
    organization_id: &str,
    project_id: &str,
) -> Result<SubscriptionQuota, String> {
    query_zhipu_team_at(ZHIPU_TEAM_QUOTA_URL, api_key, organization_id, project_id).await
}

/// 团队版额度查询。`quota_url_base` 为不含 query 的 quota 端点;团队版与个人版同路径,
/// 靠 `?type=2` 区分(在此拼上)。拆出 url 参数便于用本地 server 测试请求形状。
async fn query_zhipu_team_at(
    quota_url_base: &str,
    api_key: &str,
    organization_id: &str,
    project_id: &str,
) -> Result<SubscriptionQuota, String> {
    let client = crate::proxy::http_client::get();
    let url = format!("{quota_url_base}?type=2");

    let request = client
        .get(&url)
        .header("Authorization", api_key) // 与个人版一致:智谱不加 Bearer 前缀
        .header("bigmodel-organization", organization_id)
        .header("bigmodel-project", project_id)
        .header("Content-Type", "application/json")
        .header("Accept-Language", "en-US,en")
        .timeout(std::time::Duration::from_secs(15));
    let body = match send_for_json(request).await? {
        JsonReply::Body(body) => body,
        JsonReply::Denied(status) => return Ok(auth_error(status)),
        JsonReply::Failed(message) => return Ok(make_error(message)),
    };

    // 团队版没有套餐不回落余额:用户是显式选的团队版,余额接口也不认组织 / 项目头,
    // 查到的未必是这个团队的钱。
    Ok(zhipu_quota_from_body(&body))
}

/// 查询编程套餐额度。瞬时传输失败(网络/超时/读体中断)返回 `Err`(前端 reject →
/// retry + 保留上次成功值);确定性失败(凭据缺失/未知域名/鉴权/非 2xx/业务错误)
/// 返回 `Ok(success:false)` 立即透出文案。判定按 reqwest 错误种类在折叠点完成。
///
/// `coding_plan_provider` 显式标识用于无法靠 base_url 区分的供应商(当前为智谱团队版
/// `zhipu_team`——其 base_url 与个人版智谱相同);其余情况走 `detect_provider`。
pub async fn get_coding_plan_quota(
    base_url: &str,
    api_key: &str,
    access_key_id: Option<&str>,
    secret_access_key: Option<&str>,
    coding_plan_provider: Option<&str>,
    team_organization_id: Option<&str>,
    team_project_id: Option<&str>,
) -> Result<SubscriptionQuota, String> {
    query_coding_plan(
        base_url,
        api_key,
        access_key_id,
        secret_access_key,
        coding_plan_provider,
        team_organization_id,
        team_project_id,
    )
    .await
    .map(CodingPlanOutcome::into_quota)
}

/// 同 [`get_coding_plan_quota`],但把「智谱账户没有 Coding Plan」单独返回,
/// 供用量查询入口改查余额。
pub(crate) async fn query_coding_plan(
    base_url: &str,
    api_key: &str,
    access_key_id: Option<&str>,
    secret_access_key: Option<&str>,
    coding_plan_provider: Option<&str>,
    team_organization_id: Option<&str>,
    team_project_id: Option<&str>,
) -> Result<CodingPlanOutcome, String> {
    use CodingPlanOutcome::Quota;

    // 智谱团队版:base_url 与个人版智谱(open.bigmodel.cn)相同,detect_provider 无法
    // 区分,必须靠显式 coding_plan_provider == "zhipu_team" 路由。需 api_key + 组织 ID
    // + 项目 ID 三者齐全,缺任一返回 NotFound 引导补全。
    if coding_plan_provider
        .map(|p| p.eq_ignore_ascii_case("zhipu_team"))
        .unwrap_or(false)
    {
        let organization_id = team_organization_id.unwrap_or("").trim();
        let project_id = team_project_id.unwrap_or("").trim();
        if api_key.trim().is_empty() || organization_id.is_empty() || project_id.is_empty() {
            return Ok(Quota(coding_plan_not_found(
                "Zhipu team plan needs the API key + organization ID + project ID",
            )));
        }
        return query_zhipu_team(api_key, organization_id, project_id)
            .await
            .map(Quota);
    }

    let provider = match detect_provider(base_url) {
        Some(p) => p,
        // 域名未命中已知套餐供应商(如第三方中转站):给出明确错误而非静默失败
        None => return Ok(Quota(coding_plan_not_found("Unknown coding plan provider"))),
    };

    // 火山方舟走控制面 AK/SK 签名(区别于其他供应商的数据面 Bearer api_key),凭据
    // 校验与查询路径都不同,单独分支提前处理。
    if let CodingPlanProvider::Volcengine = provider {
        let ak = access_key_id.unwrap_or("").trim();
        let sk = secret_access_key.unwrap_or("").trim();
        if ak.is_empty() || sk.is_empty() {
            return Ok(Quota(coding_plan_not_found(
                "Volcengine usage query needs the account AccessKey ID + Secret (not the inference API key)",
            )));
        }
        return query_volcengine(base_url, ak, sk).await.map(Quota);
    }

    // 其余供应商:数据面 Bearer api_key。
    // 与 balance::get_balance 一致:给出明确错误,避免 footer 显示无信息的失败
    if api_key.trim().is_empty() {
        return Ok(Quota(coding_plan_not_found("API key is empty")));
    }

    let quota = match provider {
        CodingPlanProvider::ZhipuCn | CodingPlanProvider::ZhipuEn => {
            return query_zhipu(base_url, api_key).await
        }
        CodingPlanProvider::Kimi => query_kimi(base_url, api_key).await,
        CodingPlanProvider::MiniMaxCn => query_minimax(api_key, true).await,
        CodingPlanProvider::MiniMaxEn => query_minimax(api_key, false).await,
        CodingPlanProvider::ZenMux => query_zenmux(base_url, api_key).await,
        CodingPlanProvider::OpencodeGo => query_opencode_go(api_key).await,
        CodingPlanProvider::CommandCode => query_command_code(api_key).await,
        CodingPlanProvider::OllamaCloud => query_ollama_cloud(api_key).await,
        CodingPlanProvider::MimoTokenPlan => query_mimo_token_plan(api_key).await,
        // 火山已在上面的 AK/SK 分支提前返回,此处不可达。
        CodingPlanProvider::Volcengine => {
            unreachable!("volcengine handled via AK/SK branch above")
        }
    };
    quota.map(Quota)
}

#[cfg(test)]
mod tests {
    use super::{
        detect_provider, detect_provider_id, kimi_quota_base, parse_afp_tiers,
        parse_coding_plan_tiers, parse_command_code_quota, parse_mimo_token_plan_tiers,
        parse_minimax_tiers, parse_ollama_cloud_tiers, parse_opencode_go_tiers,
        parse_zhipu_token_tiers, query_command_code_at, query_kimi_at, query_zhipu_at,
        query_zhipu_team_at, volcengine_canonical_query, volcengine_is_auth_error_code,
        volcengine_region, volcengine_response_error, volcengine_sign, zhipu_outcome_from_body,
        zhipu_quota_base, CodingPlanOutcome, CodingPlanProvider, CredentialStatus, TIER_CREDITS,
        TIER_FIVE_HOUR, TIER_MONTHLY, TIER_WEEKLY_LIMIT,
    };
    use serde_json::json;

    #[tokio::test]
    async fn kimi_global_monthly_tiers_do_not_invent_weekly_quota() {
        ensure_no_proxy_for_loopback();
        let body = json!({
            "limits": [{"detail": {"limit": "100", "remaining": "77",
                "resetTime": "2030-01-01T05:00:00Z"}}],
            "usages": {
                "limit_5h": {"used_ratio": 0.23, "reset_time": "2030-01-01T05:00:00Z"},
                "limit_month_total": {"used_ratio": 0.4, "reset_time": "2030-02-01T00:00:00Z"},
                "limit_month_code": {"used_ratio": 0.35, "reset_time": "2030-02-01T00:00:00Z"}
            }
        });
        let (base, paths, handle) =
            spawn_sequence_server(vec![Some(http_response("200 OK", &body.to_string()))]);
        let quota = query_kimi_at(&format!("{base}/coding/v1/"), "test-key")
            .await
            .unwrap();
        handle.join().unwrap();

        assert_eq!(*paths.lock().unwrap(), ["/coding/v1/usages"]);
        assert!(quota.success);
        assert_eq!(quota.tiers.len(), 3);
        for (tier, (name, used, reset)) in quota.tiers.iter().zip([
            (TIER_FIVE_HOUR, 23.0, "2030-01-01T05:00:00Z"),
            ("kimi_monthly_total", 40.0, "2030-02-01T00:00:00Z"),
            ("kimi_monthly_code", 35.0, "2030-02-01T00:00:00Z"),
        ]) {
            assert_eq!(tier.name, name);
            assert!((tier.utilization - used).abs() < 1e-9);
            assert_eq!(tier.resets_at.as_deref(), Some(reset));
        }
    }

    #[tokio::test]
    async fn kimi_ratio_only_tiers_support_weekly_and_zero_usage() {
        ensure_no_proxy_for_loopback();
        let body = json!({"usages": {
            "limit_5h": {"used_ratio": 0, "reset_time": "2030-01-01T05:00:00Z"},
            "limit_7d": {"used_ratio": "0.6", "reset_time": "2030-01-08T00:00:00Z"}
        }});
        let (base, handle) = spawn_once_server(Some(http_response("200 OK", &body.to_string())));
        let quota = query_kimi_at(&base, "test-key").await.unwrap();
        handle.join().unwrap();

        assert_eq!(quota.tiers.len(), 2);
        assert_eq!(quota.tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(quota.tiers[0].utilization, 0.0);
        assert_eq!(quota.tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(quota.tiers[1].utilization, 60.0);
        assert_eq!(
            quota.tiers[1].resets_at.as_deref(),
            Some("2030-01-08T00:00:00Z")
        );
    }

    #[tokio::test]
    async fn kimi_legacy_counters_take_precedence_without_duplicate_tiers() {
        ensure_no_proxy_for_loopback();
        let body = json!({
            "limits": [{"detail": {"limit": "100", "remaining": "75"}}],
            "usage": {"limit": "100", "remaining": "40"},
            "usages": {"limit_5h": {"used_ratio": 0}, "limit_7d": {"used_ratio": 0}}
        });
        let (base, handle) = spawn_once_server(Some(http_response("200 OK", &body.to_string())));
        let quota = query_kimi_at(&base, "test-key").await.unwrap();
        handle.join().unwrap();

        assert_eq!(quota.tiers.len(), 2);
        assert_eq!(quota.tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(quota.tiers[0].utilization, 25.0);
        assert_eq!(quota.tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(quota.tiers[1].utilization, 60.0);
    }

    #[tokio::test]
    async fn kimi_invalid_ratio_fields_do_not_create_quota_tiers() {
        ensure_no_proxy_for_loopback();
        let body = json!({"usages": {
            "limit_5h": null,
            "limit_7d": {"reset_time": "2030-01-08T00:00:00Z"},
            "limit_month_total": {"used_ratio": "NaN"},
            "limit_month_code": {"used_ratio": -0.1}
        }});
        let (base, handle) = spawn_once_server(Some(http_response("200 OK", &body.to_string())));
        let quota = query_kimi_at(&base, "test-key").await.unwrap();
        handle.join().unwrap();

        assert!(quota.success);
        assert!(quota.tiers.is_empty());
    }

    #[test]
    fn kimi_detects_cn_and_global_hosts() {
        // 国内站(kimi.com)与海外站(kimi.ai,「Kimi For Coding Global」)都命中;
        // 大小写不敏感;各 app 的 base_url 形态(带不带 /v1、尾斜杠)都要认
        for base_url in [
            "https://api.kimi.com/coding/",
            "https://api.kimi.com/coding/v1",
            "https://api.kimi.ai/coding",
            "https://api.kimi.ai/coding/",
            "https://api.kimi.ai/coding/v1",
            "HTTPS://API.KIMI.AI/CODING/v1",
        ] {
            assert!(
                matches!(detect_provider(base_url), Some(CodingPlanProvider::Kimi)),
                "{base_url} must detect as Kimi"
            );
        }
        // 近似 host 不命中(与前端 regex 一致)
        assert!(detect_provider("https://api.kimi.ai.evil.example/coding").is_none());
        assert!(detect_provider("https://api.kimi.com.evil.example/coding").is_none());
    }

    #[test]
    fn kimi_quota_base_follows_region_and_normalizes_path() {
        // 海外 base_url(含 Claude Code 式 `…/coding/` 尾斜杠写法)归一到全球根
        for base_url in [
            "https://api.kimi.ai/coding",
            "https://api.kimi.ai/coding/",
            "HTTPS://API.KIMI.AI.:443/CODING/v1",
        ] {
            assert_eq!(kimi_quota_base(base_url), "https://api.kimi.ai/coding/v1");
        }
        // 国内 base_url 归一到国内根
        for base_url in [
            "https://api.kimi.com/coding",
            "https://api.kimi.com/coding/",
            "https://api.kimi.com/coding/v1",
            "https://api.kimi.com/coding/v1?region=api.kimi.ai",
        ] {
            assert_eq!(kimi_quota_base(base_url), "https://api.kimi.com/coding/v1");
        }
    }

    #[test]
    fn minimax_cn_detects_current_and_legacy_hosts() {
        for base_url in [
            "https://api.minimax.cn/v1",
            "https://API.MINIMAX.CN/anthropic",
            "https://api.minimaxi.com/v1",
        ] {
            assert!(matches!(
                detect_provider(base_url),
                Some(CodingPlanProvider::MiniMaxCn)
            ));
        }
        assert!(matches!(
            detect_provider("https://api.minimax.io/v1"),
            Some(CodingPlanProvider::MiniMaxEn)
        ));
        assert!(detect_provider("https://api.minimax.cn.example.com/v1").is_none());
        assert!(detect_provider("https://api.minimax.io.example.com/v1").is_none());
    }

    #[test]
    fn command_code_detects_both_provider_base_variants() {
        assert!(matches!(
            detect_provider("https://api.commandcode.ai/provider"),
            Some(CodingPlanProvider::CommandCode)
        ));
        assert!(matches!(
            detect_provider("https://api.commandcode.ai/provider/v1"),
            Some(CodingPlanProvider::CommandCode)
        ));
        assert!(matches!(
            detect_provider("https://API.CommandCode.ai/provider?x=1"),
            Some(CodingPlanProvider::CommandCode)
        ));
        assert!(detect_provider("https://commandcode.ai/provider").is_none());
        assert!(detect_provider("https://api.commandcode.ai/providers").is_none());
        assert!(detect_provider("https://api.commandcode.ai/provider-v2").is_none());
    }

    #[test]
    fn command_code_maps_balance_and_window_limits() {
        let credits = json!({
            "credits": {
                "planId": "provider",
                "monthlyCredits": 12.5,
                "purchasedCredits": 3.0,
                "freeCredits": 0.5,
                "windowLimits": {
                    "limited": true,
                    "fiveHour": {
                        "used": 4.0,
                        "cap": 14.0,
                        "resetAt": "2026-09-12T18:00:00.000Z"
                    },
                    "weekly": {
                        "used": 12.0,
                        "cap": 40.0,
                        "resetAt": "2026-09-16T00:00:00.000Z"
                    }
                }
            }
        });
        let subscription = json!({
            "data": {
                "planId": "goat",
                "status": "active",
                "currentPeriodStart": "2026-09-01T00:00:00.000Z",
                "currentPeriodEnd": "2026-10-01T00:00:00.000Z"
            }
        });
        let summary = json!({ "totalCost": 7.0 });

        let quota = parse_command_code_quota(&credits, Some(&subscription), &summary);

        assert!(quota.success);
        assert!(matches!(quota.credential_status, CredentialStatus::Valid));
        assert_eq!(quota.credential_message.as_deref(), Some("goat"));
        assert_eq!(quota.tiers.len(), 3);
        assert_eq!(quota.tiers[0].name, TIER_FIVE_HOUR);
        assert!((quota.tiers[0].utilization - (4.0 / 14.0 * 100.0)).abs() < 1e-9);
        assert_eq!(
            quota.tiers[0].resets_at.as_deref(),
            Some("2026-09-12T18:00:00.000Z")
        );
        assert_eq!(quota.tiers[1].name, TIER_WEEKLY_LIMIT);
        assert!((quota.tiers[1].utilization - 30.0).abs() < 1e-9);
        assert_eq!(quota.tiers[2].name, TIER_MONTHLY);
        assert!((quota.tiers[2].utilization - (7.0 / 23.0 * 100.0)).abs() < 1e-9);
        assert_eq!(quota.tiers[2].used_value_usd, None);
        assert_eq!(quota.tiers[2].max_value_usd, None);
        assert_eq!(
            quota.tiers[2].resets_at.as_deref(),
            Some("2026-10-01T00:00:00.000Z")
        );
    }

    #[test]
    fn command_code_parses_real_goat_subscription_shape() {
        let credits = json!({
            "credits": {
                "belowThreshold": false,
                "creditThreshold": 0,
                "monthlyCredits": 70,
                "purchasedCredits": 0,
                "freeCredits": 0
            },
            "windowLimits": {
                "limited": true,
                "exceeded": null,
                "fiveHour": {
                    "used": 0,
                    "cap": 14,
                    "exceeded": false,
                    "resetAt": 0
                },
                "weekly": {
                    "used": 0,
                    "cap": 35,
                    "exceeded": false,
                    "resetAt": 0
                }
            }
        });
        let subscription = json!({
            "success": true,
            "data": {
                "status": "active",
                "currentPeriodStart": "2026-09-13T01:01:27.000Z",
                "currentPeriodEnd": "2026-10-13T01:01:27.000Z",
                "planId": "individual-goat"
            }
        });
        let summary = json!({
            "totalCost": 0,
            "periodBasis": "billing-period"
        });

        let quota = parse_command_code_quota(&credits, Some(&subscription), &summary);

        assert!(quota.success);
        assert!(matches!(quota.credential_status, CredentialStatus::Valid));
        assert_eq!(quota.credential_message.as_deref(), Some("individual-goat"));
        assert_eq!(quota.tiers.len(), 3);
        assert_eq!(quota.tiers[0].name, TIER_FIVE_HOUR);
        assert!((quota.tiers[0].utilization - 0.0).abs() < 1e-9);
        assert!(quota.tiers[0].resets_at.is_none());
        assert_eq!(quota.tiers[1].name, TIER_WEEKLY_LIMIT);
        assert!((quota.tiers[1].utilization - 0.0).abs() < 1e-9);
        assert!(quota.tiers[1].resets_at.is_none());
        assert_eq!(quota.tiers[2].name, TIER_MONTHLY);
        assert!((quota.tiers[2].utilization - 0.0).abs() < 1e-9);
        assert_eq!(quota.tiers[2].used_value_usd, None);
        assert_eq!(quota.tiers[2].max_value_usd, None);
        assert_eq!(
            quota.tiers[2].resets_at.as_deref(),
            Some("2026-10-13T01:01:27.000Z")
        );
    }

    #[test]
    fn command_code_pay_as_you_go_has_balance_without_subscription() {
        let credits = json!({
            "credits": {
                "planId": "provider",
                "monthlyCredits": 0,
                "purchasedCredits": 18.25,
                "freeCredits": 0,
                "windowLimits": { "limited": false }
            }
        });

        let quota = parse_command_code_quota(
            &credits,
            None,
            &json!({
                "totalCost": 0
            }),
        );

        assert!(quota.success);
        assert_eq!(quota.credential_message.as_deref(), Some("provider"));
        assert_eq!(quota.tiers.len(), 1);
        assert_eq!(quota.tiers[0].name, TIER_MONTHLY);
        assert_eq!(quota.tiers[0].used_value_usd, None);
        assert_eq!(quota.tiers[0].max_value_usd, None);
        assert!(quota.tiers[0].resets_at.is_none());
    }

    #[test]
    fn command_code_skips_malformed_windows() {
        let credits = json!({
            "credits": {
                "monthlyCredits": 1,
                "purchasedCredits": 0,
                "freeCredits": 0,
                "windowLimits": {
                    "limited": true,
                    "fiveHour": { "used": 1, "cap": 0 },
                    "weekly": { "used": 1, "cap": 10, "resetAt": "2026-09-16T00:00:00Z" }
                }
            }
        });

        let quota = parse_command_code_quota(
            &credits,
            None,
            &json!({
                "totalCost": 1
            }),
        );

        assert!(quota.success);
        assert_eq!(quota.tiers.len(), 2);
        assert_eq!(quota.tiers[0].name, TIER_WEEKLY_LIMIT);
        assert_eq!(quota.tiers[1].name, TIER_MONTHLY);
    }

    #[test]
    fn command_code_missing_credits_is_deterministic_error() {
        let quota = parse_command_code_quota(&json!({}), None, &json!({}));
        assert!(!quota.success);
        assert!(quota
            .error
            .expect("error")
            .contains("Missing 'credits' field"));
    }

    #[test]
    fn command_code_missing_total_cost_is_deterministic_error() {
        let quota = parse_command_code_quota(&json!({ "credits": {} }), None, &json!({}));

        assert!(!quota.success);
        assert!(quota
            .error
            .expect("error")
            .contains("Missing 'totalCost' field"));
    }

    #[tokio::test]
    async fn command_code_401_maps_to_expired_credentials() {
        ensure_no_proxy_for_loopback();
        let (base_url, handle) = spawn_once_server(Some(http_response("401 Unauthorized", "{}")));

        let quota = query_command_code_at(&base_url, "k")
            .await
            .expect("auth failure must be deterministic");

        assert!(!quota.success);
        assert!(matches!(quota.credential_status, CredentialStatus::Expired));
        assert!(quota
            .error
            .expect("error")
            .contains("Authentication failed (HTTP 401"));
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn command_code_403_is_reported_with_body() {
        ensure_no_proxy_for_loopback();
        let (base_url, handle) = spawn_once_server(Some(http_response(
            "403 Forbidden",
            r#"{"error":{"code":"upgrade_required"}}"#,
        )));

        let quota = query_command_code_at(&base_url, "k")
            .await
            .expect("403 must be deterministic");

        assert!(!quota.success);
        assert!(quota.error.expect("error").contains("HTTP 403"));
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn command_code_429_is_reported_as_deterministic_error() {
        ensure_no_proxy_for_loopback();
        let (base_url, handle) =
            spawn_once_server(Some(http_response("429 Too Many Requests", "slow down")));

        let quota = query_command_code_at(&base_url, "k")
            .await
            .expect("non-2xx must remain a deterministic result");

        assert!(!quota.success);
        assert!(quota.error.expect("error").contains("HTTP 429"));
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn command_code_invalid_json_is_deterministic_parse_error() {
        ensure_no_proxy_for_loopback();
        let (base_url, handle) = spawn_once_server(Some(http_response("200 OK", "not-json")));

        let quota = query_command_code_at(&base_url, "k")
            .await
            .expect("invalid JSON must be deterministic");

        assert!(!quota.success);
        assert!(quota
            .error
            .expect("error")
            .contains("Failed to parse response"));
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn command_code_subscription_transient_is_err() {
        ensure_no_proxy_for_loopback();
        let responses = vec![
            Some(http_response(
                "200 OK",
                r#"{"success":true,"user":{"id":"u-1"},"org":{"id":"org-1"}}"#,
            )),
            Some(http_response(
                "200 OK",
                r#"{"credits":{"monthlyCredits":70,"purchasedCredits":0,"freeCredits":0},"windowLimits":{"limited":true,"fiveHour":{"used":0,"cap":14},"weekly":{"used":0,"cap":35}}}"#,
            )),
            None,
        ];
        let (base_url, _, handle) = spawn_sequence_server(responses);

        query_command_code_at(&base_url, "k")
            .await
            .expect_err("subscription 传输失败必须返回 Err,不能降级成无订阅");
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn command_code_summary_transient_is_err() {
        ensure_no_proxy_for_loopback();
        let responses = vec![
            Some(http_response(
                "200 OK",
                r#"{"success":true,"user":{"id":"u-1"},"org":{"id":"org-1"}}"#,
            )),
            Some(http_response(
                "200 OK",
                r#"{"credits":{"monthlyCredits":70,"purchasedCredits":0,"freeCredits":0},"windowLimits":{"limited":true,"fiveHour":{"used":0,"cap":14},"weekly":{"used":0,"cap":35}}}"#,
            )),
            Some(http_response(
                "200 OK",
                r#"{"success":true,"data":{"status":"active","currentPeriodStart":"2026-09-13T01:01:27.000Z","currentPeriodEnd":"2026-10-13T01:01:27.000Z","planId":"individual-goat"}}"#,
            )),
            None,
        ];
        let (base_url, _, handle) = spawn_sequence_server(responses);

        query_command_code_at(&base_url, "k")
            .await
            .expect_err("summary 传输失败必须返回 Err,不能把已用量降级成 0");
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn command_code_summary_http_error_is_deterministic() {
        ensure_no_proxy_for_loopback();
        let responses = vec![
            Some(http_response(
                "200 OK",
                r#"{"success":true,"user":{"id":"u-1"},"org":{"id":"org-1"}}"#,
            )),
            Some(http_response(
                "200 OK",
                r#"{"credits":{"monthlyCredits":70,"purchasedCredits":0,"freeCredits":0},"windowLimits":{"limited":true,"fiveHour":{"used":0,"cap":14},"weekly":{"used":0,"cap":35}}}"#,
            )),
            Some(http_response(
                "200 OK",
                r#"{"success":true,"data":{"status":"active","currentPeriodStart":"2026-09-13T01:01:27.000Z","currentPeriodEnd":"2026-10-13T01:01:27.000Z","planId":"individual-goat"}}"#,
            )),
            Some(http_response("500 Internal Server Error", "{}")),
        ];
        let (base_url, _, handle) = spawn_sequence_server(responses);

        let quota = query_command_code_at(&base_url, "k")
            .await
            .expect("summary 非 2xx 必须是确定性结果");
        assert!(!quota.success);
        assert!(quota.error.expect("error").contains("HTTP 500"));
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn command_code_queries_all_four_alpha_endpoints_in_order() {
        ensure_no_proxy_for_loopback();
        let responses = vec![
            Some(http_response(
                "200 OK",
                r#"{"success":true,"user":{"id":"u-1"},"org":{"id":"org-1"}}"#,
            )),
            Some(http_response(
                "200 OK",
                r#"{"credits":{"belowThreshold":false,"creditThreshold":0,"monthlyCredits":70,"purchasedCredits":0,"freeCredits":0},"windowLimits":{"limited":true,"exceeded":null,"fiveHour":{"used":0,"cap":14,"exceeded":false,"resetAt":0},"weekly":{"used":0,"cap":35,"exceeded":false,"resetAt":0}}}"#,
            )),
            Some(http_response(
                "200 OK",
                r#"{"success":true,"data":{"status":"active","currentPeriodStart":"2026-09-13T01:01:27.000Z","currentPeriodEnd":"2026-10-13T01:01:27.000Z","planId":"individual-goat"}}"#,
            )),
            Some(http_response(
                "200 OK",
                r#"{"totalCost":0,"periodBasis":"billing-period"}"#,
            )),
        ];
        let (base_url, captured_paths, handle) = spawn_sequence_server(responses);

        let quota = query_command_code_at(&base_url, "k")
            .await
            .expect("完整链路必须返回成功");

        let paths = captured_paths.lock().unwrap().clone();
        assert_eq!(
            paths,
            vec![
                "/alpha/whoami?limits=1",
                "/alpha/billing/credits?orgId=org-1",
                "/alpha/billing/subscriptions?orgId=org-1",
                "/alpha/usage/summary?since=2026-09-13T01%3A01%3A27.000Z&orgId=org-1"
            ]
        );
        assert!(quota.success);
        assert_eq!(quota.tiers.len(), 3);
        assert_eq!(quota.tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(quota.tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(quota.tiers[2].name, TIER_MONTHLY);
        handle.join().expect("server thread");
    }

    #[test]
    fn opencode_go_detects_current_and_legacy_bases_but_not_zen() {
        // Claude Desktop 预设 base 是 /inference/go/anthropic,Codex/OpenCode/Pi
        // 是 /inference/go/v1;旧入口 /zen/go[/v1] 仍可用,也要命中;Zen 按量版
        // (/zen/v1)无用量 API,不得命中。
        assert!(matches!(
            detect_provider("https://opencode.ai/inference/go/anthropic"),
            Some(CodingPlanProvider::OpencodeGo)
        ));
        assert!(matches!(
            detect_provider("https://opencode.ai/inference/go/v1"),
            Some(CodingPlanProvider::OpencodeGo)
        ));
        assert!(matches!(
            detect_provider("https://opencode.ai/zen/go"),
            Some(CodingPlanProvider::OpencodeGo)
        ));
        assert!(matches!(
            detect_provider("https://opencode.ai/zen/go/v1"),
            Some(CodingPlanProvider::OpencodeGo)
        ));
        assert!(detect_provider("https://opencode.ai/zen/v1").is_none());
        assert!(detect_provider("https://opencode.ai/inference/v1").is_none());
    }

    #[test]
    fn mimo_token_plan_detects_plan_host_only() {
        for base_url in [
            "https://token-plan-cn.xiaomimimo.com/anthropic",
            "https://token-plan-cn.xiaomimimo.com/v1",
            "HTTPS://TOKEN-PLAN-CN.XIAOMIMIMO.COM/",
        ] {
            assert!(matches!(
                detect_provider(base_url),
                Some(CodingPlanProvider::MimoTokenPlan)
            ));
            assert_eq!(detect_provider_id(base_url), Some("mimo"));
        }
        // 按量付费地址走余额查询;中转站路径里带着套餐域名也不算
        assert!(detect_provider("https://api.xiaomimimo.com/anthropic").is_none());
        assert!(
            detect_provider("https://relay.example.com/token-plan-cn.xiaomimimo.com/v1").is_none()
        );
        assert!(detect_provider("https://token-plan-cn.xiaomimimo.com.example.com/v1").is_none());
    }

    /// 官方文档示例原文(mimo.mi.com/docs/zh-CN/api/asset/credits-get,2026-11-03)。
    #[test]
    fn mimo_token_plan_maps_credits_to_one_tier_with_utc_period_end() {
        let body = json!({
            "object": "token_plan",
            "plan_code": "pro",
            "period": { "start_at": "2026-09-21 23:59:59", "end_at": "2027-09-21 23:59:59" },
            "quota": {
                "total_credits": 10000000,
                "used_credits": 1500000,
                "remaining_credits": 8500000
            },
            "auto_renew": false,
            "claw_enabled": false
        });
        let tiers = parse_mimo_token_plan_tiers(&body);
        assert_eq!(tiers.len(), 1);
        assert_eq!(tiers[0].name, TIER_CREDITS);
        assert!((tiers[0].utilization - 15.0).abs() < 1e-9);
        assert_eq!(
            tiers[0].resets_at.as_deref(),
            Some("2027-09-21T23:59:59+00:00")
        );

        // 只给剩余也能算;超用封顶 100%
        let tiers = parse_mimo_token_plan_tiers(&json!({
            "quota": { "total_credits": 200, "remaining_credits": 50 }
        }));
        assert!((tiers[0].utilization - 75.0).abs() < 1e-9);
        assert!(tiers[0].resets_at.is_none());
        let tiers = parse_mimo_token_plan_tiers(&json!({
            "quota": { "total_credits": 100, "used_credits": 120 }
        }));
        assert!((tiers[0].utilization - 100.0).abs() < 1e-9);
    }

    #[test]
    fn mimo_token_plan_without_credits_has_no_tier() {
        for body in [
            json!({}),
            json!({ "quota": { "total_credits": 0, "used_credits": 0 } }),
            json!({ "quota": { "total_credits": 100 } }),
            json!({ "error": { "message": "Invalid API key" } }),
        ] {
            assert!(parse_mimo_token_plan_tiers(&body).is_empty(), "{body}");
        }
    }

    #[test]
    fn ollama_cloud_detects_cloud_host_only() {
        for base_url in [
            "https://ollama.com",
            "https://ollama.com/v1",
            "https://OLLAMA.com/",
        ] {
            assert!(matches!(
                detect_provider(base_url),
                Some(CodingPlanProvider::OllamaCloud)
            ));
        }
        assert!(detect_provider("http://localhost:11434").is_none());
        assert!(detect_provider("http://127.0.0.1:11434/v1").is_none());
        assert!(detect_provider("https://ollama.com.example.com/v1").is_none());
    }

    #[test]
    fn ollama_cloud_current_plan_maps_included_credit_to_monthly() {
        let body = json!({
            "included": {
                "balance_usd": 72.5,
                "allowance_usd": 100,
                "period": {
                    "from": "2026-11-01T00:00:00Z",
                    "until": "2026-12-01T00:00:00Z"
                }
            },
            "purchased": { "balance_usd": 25 }
        });
        let tiers = parse_ollama_cloud_tiers(&body);
        assert_eq!(tiers.len(), 1);
        assert_eq!(tiers[0].name, TIER_MONTHLY);
        assert!((tiers[0].utilization - 27.5).abs() < 1e-9);
        assert_eq!(tiers[0].resets_at.as_deref(), Some("2026-12-01T00:00:00Z"));
    }

    #[test]
    fn ollama_cloud_legacy_plan_maps_session_and_weekly() {
        let body = json!({
            "included": {
                "session": { "remaining_percent": 80, "resets_at": "2026-11-10T13:00:00Z" },
                "weekly": { "remaining_percent": 35.5, "resets_at": "2026-11-14T00:00:00Z" }
            }
        });
        let tiers = parse_ollama_cloud_tiers(&body);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert!((tiers[0].utilization - 20.0).abs() < 1e-9);
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert!((tiers[1].utilization - 64.5).abs() < 1e-9);
        assert_eq!(tiers[1].resets_at.as_deref(), Some("2026-11-14T00:00:00Z"));
        assert!(parse_ollama_cloud_tiers(&json!({})).is_empty());
    }

    #[test]
    fn opencode_go_three_windows_map_to_known_tiers() {
        let body = json!({
            "usage": {
                "rolling": { "status": "ok", "percent": 37, "resetsAt": "2026-08-26T14:12:03.000Z" },
                "weekly":  { "status": "ok", "percent": 62, "resetsAt": "2026-08-31T00:00:00.000Z" },
                "monthly": { "status": "rate-limited", "percent": 100, "resetsAt": "2026-09-11T00:00:00.000Z" }
            }
        });
        let tiers = parse_opencode_go_tiers(&body);
        assert_eq!(tiers.len(), 3);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 37.0);
        assert_eq!(
            tiers[0].resets_at.as_deref(),
            Some("2026-08-26T14:12:03.000Z")
        );
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 62.0);
        assert_eq!(tiers[2].name, TIER_MONTHLY);
        assert_eq!(tiers[2].utilization, 100.0);
    }

    #[test]
    fn opencode_go_zero_percent_drops_placeholder_reset_time() {
        // percent==0 时上游 resetsAt 是 now+窗口时长的占位值(整窗早已清零),
        // 不能当真实重置时刻展示倒计时。
        let body = json!({
            "usage": {
                "rolling": { "status": "ok", "percent": 0, "resetsAt": "2026-08-26T15:00:00.000Z" }
            }
        });
        let tiers = parse_opencode_go_tiers(&body);
        assert_eq!(tiers.len(), 1);
        assert_eq!(tiers[0].utilization, 0.0);
        assert!(tiers[0].resets_at.is_none());
    }

    #[test]
    fn opencode_go_partial_windows_skip_malformed() {
        // 防御:未文档化端点上线当天就改过形态——坏窗口跳过、好窗口保留,
        // percent 兼容字符串数字。
        let body = json!({
            "usage": {
                "rolling": { "status": "ok" },
                "weekly":  { "status": "ok", "percent": "12" },
                "monthly": null
            }
        });
        let tiers = parse_opencode_go_tiers(&body);
        assert_eq!(tiers.len(), 1);
        assert_eq!(tiers[0].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[0].utilization, 12.0);
    }

    #[test]
    fn opencode_go_legacy_flat_shape_returns_empty() {
        // 2026-08-11 上线当天仅存在 53 分钟的旧扁平形态:不兼容,返回空
        // 由调用方按「响应形态不认识」报错。
        let body = json!({
            "useBalance": false,
            "rollingUsage": { "status": "ok", "usagePercent": 37, "resetInSec": 3600 }
        });
        assert!(parse_opencode_go_tiers(&body).is_empty());
    }

    #[test]
    fn zhipu_new_plan_two_tiers_sorted_by_reset_time() {
        // 新套餐:两条 TOKENS_LIMIT,nextResetTime 较近的归 five_hour、较远的归 weekly_limit。
        // 故意把"周限"放数组前面,验证不依赖输入顺序。
        let data = json!({
            "limits": [
                { "type": "TOKENS_LIMIT", "percentage": 53.0, "nextResetTime": 2_000_000_000_000_i64 },
                { "type": "TOKENS_LIMIT", "percentage": 44.0, "nextResetTime": 1_000_000_000_000_i64 },
                { "type": "TIME_LIMIT",   "percentage":  7.0 },
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 44.0);
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 53.0);
    }

    #[test]
    fn zhipu_old_plan_single_tier_falls_back_to_five_hour() {
        // 老套餐(2026-02-12 前订阅):仅一条 TOKENS_LIMIT,无周限。
        let data = json!({
            "limits": [
                {
                    "type": "TOKENS_LIMIT",
                    "percentage": 2.0,
                    "nextResetTime": 1_774_967_594_803_i64
                },
                { "type": "TIME_LIMIT", "percentage": 0.0 }
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 1);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 2.0);
    }

    #[test]
    fn zhipu_no_token_limits_returns_empty() {
        let data = json!({ "limits": [{ "type": "TIME_LIMIT", "percentage": 5.0 }] });
        assert!(parse_zhipu_token_tiers(&data).is_empty());
    }

    #[test]
    fn zhipu_missing_reset_time_is_five_hour_when_weekly_has_reset() {
        // 真实反馈:5 小时桶为 0% 时可能没有 nextResetTime;每周桶带 reset。
        // 这种形态不能按 reset 升序把每周桶误判为 five_hour。
        let data = json!({
            "limits": [
                { "type": "TOKENS_LIMIT", "percentage": 25.0, "nextResetTime": 2_000_000_000_000_i64 },
                { "type": "TOKENS_LIMIT", "percentage": 0.0 }
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 0.0);
        assert!(tiers[0].resets_at.is_none());
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 25.0);
        assert!(tiers[1].resets_at.is_some());
    }

    #[test]
    fn zhipu_type_is_case_insensitive() {
        // 防御性:上游若把 "TOKENS_LIMIT" 改成 "tokens_limit"(仅大小写变化)仍能识别。
        // 注意:分隔符差异(如 "TokensLimit" 去掉下划线)不在兼容范围。
        let data = json!({
            "limits": [
                { "type": "tokens_limit", "percentage": 12.0, "nextResetTime": 1_000_000_000_000_i64 },
                { "type": "Tokens_Limit", "percentage": 34.0, "nextResetTime": 2_000_000_000_000_i64 }
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 12.0);
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 34.0);
    }

    #[test]
    fn zhipu_invalid_percentage_falls_back_to_zero() {
        // percentage 为字符串或 null 时不应崩溃,按 0 处理(仍展示 tier,但用量为 0)。
        let data = json!({
            "limits": [
                { "type": "TOKENS_LIMIT", "percentage": "invalid", "nextResetTime": 1_000_000_000_000_i64 },
                { "type": "TOKENS_LIMIT", "percentage": null,      "nextResetTime": 2_000_000_000_000_i64 }
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].utilization, 0.0);
        assert_eq!(tiers[1].utilization, 0.0);
    }

    #[test]
    fn zhipu_unit_field_overrides_reset_order_when_weekly_resets_sooner() {
        // 真实案例(issue #3036,2026-06-10 再次复现):每周周期末尾,周桶比
        // 5 小时桶更早重置。官网真实值:5h 用 1%(约 5h 后重置)、每周用 42%
        // (约 1h 后重置)。旧逻辑按 reset 升序必然标反,unit 字段须优先。
        let data = json!({
            "limits": [
                { "type": "TOKENS_LIMIT", "unit": 6, "number": 7, "percentage": 42.0, "nextResetTime": 1_000_003_600_000_i64 },
                { "type": "TOKENS_LIMIT", "unit": 3, "number": 5, "percentage": 1.0,  "nextResetTime": 1_000_018_000_000_i64 }
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 1.0);
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 42.0);
    }

    #[test]
    fn zhipu_weekly_unit_six_number_one_variant() {
        // z.ai 也观测过 (unit:6, number:1) 表示每周窗口(按"1 周"计),
        // 分类只看 unit,number 取值不影响。
        let data = json!({
            "limits": [
                { "type": "TOKENS_LIMIT", "unit": 6, "number": 1, "percentage": 30.0, "nextResetTime": 1_000_000_000_000_i64 },
                { "type": "TOKENS_LIMIT", "unit": 3, "number": 5, "percentage": 10.0, "nextResetTime": 2_000_000_000_000_i64 }
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 10.0);
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 30.0);
    }

    #[test]
    fn zhipu_partial_unit_fields_fill_remaining_slot() {
        // 只有周桶带 unit 时,缺 unit 的另一条应填入剩下的 five_hour 槽位,
        // 即便它的 reset 更晚——显式分类结果不受时间排序干扰。
        let data = json!({
            "limits": [
                { "type": "TOKENS_LIMIT", "unit": 6, "number": 7, "percentage": 42.0, "nextResetTime": 1_000_000_000_000_i64 },
                { "type": "TOKENS_LIMIT", "percentage": 1.0, "nextResetTime": 2_000_000_000_000_i64 }
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 1.0);
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 42.0);
    }

    #[test]
    fn zhipu_unknown_unit_values_fall_back_to_reset_order() {
        // 未识别的 unit 枚举值不猜语义,整体回落旧的重置时间启发式。
        let data = json!({
            "limits": [
                { "type": "TOKENS_LIMIT", "unit": 9, "percentage": 44.0, "nextResetTime": 1_000_000_000_000_i64 },
                { "type": "TOKENS_LIMIT", "unit": 9, "percentage": 53.0, "nextResetTime": 2_000_000_000_000_i64 }
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 44.0);
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 53.0);
    }

    #[test]
    fn zhipu_duplicate_unit_classification_fills_other_slot() {
        // 防御性:两条都标成 5 小时窗(上游异常)时,第一条占 five_hour,
        // 第二条降级走兜底填入 weekly,保证不丢数据也不 panic。
        let data = json!({
            "limits": [
                { "type": "TOKENS_LIMIT", "unit": 3, "number": 5, "percentage": 10.0, "nextResetTime": 1_000_000_000_000_i64 },
                { "type": "TOKENS_LIMIT", "unit": 3, "number": 5, "percentage": 20.0, "nextResetTime": 2_000_000_000_000_i64 }
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 10.0);
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 20.0);
    }

    #[test]
    fn zhipu_more_than_two_token_limits_keeps_first_two() {
        // 防御性:智谱当前最多两条 TOKENS_LIMIT,若上游意外增加第三条应被丢弃,避免命名空缺。
        let data = json!({
            "limits": [
                { "type": "TOKENS_LIMIT", "percentage": 1.0, "nextResetTime": 1_000_000_000_000_i64 },
                { "type": "TOKENS_LIMIT", "percentage": 2.0, "nextResetTime": 2_000_000_000_000_i64 },
                { "type": "TOKENS_LIMIT", "percentage": 3.0, "nextResetTime": 3_000_000_000_000_i64 }
            ]
        });
        let tiers = parse_zhipu_token_tiers(&data);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
    }

    // ── MiniMax ──

    #[test]
    fn minimax_general_two_tiers_from_remaining_percent() {
        // 主路径:general 桶 5h 剩 98% / weekly 剩 95% → 已用 2% / 5%
        let body = json!({
            "model_remains": [
                {
                    "model_name": "general",
                    "current_interval_remaining_percent": 98.0,
                    "current_weekly_remaining_percent": 95.0,
                    "current_interval_status": 1,
                    "current_weekly_status": 1,
                    "end_time": 1_780_329_600_000_i64,
                    "weekly_end_time": 1_780_848_000_000_i64
                },
                {
                    "model_name": "video",
                    "current_interval_remaining_percent": 100.0,
                    "current_weekly_remaining_percent": 100.0
                }
            ],
            "base_resp": { "status_code": 0, "status_msg": "success" }
        });
        let tiers = parse_minimax_tiers(&body);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 2.0);
        assert!(tiers[0].resets_at.is_some());
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 5.0);
        assert!(tiers[1].resets_at.is_some());
    }

    #[test]
    fn minimax_skips_video_and_finds_general_in_any_position() {
        // 防御性:即使 video 排在数组前面,general 排在后面,仍应被定位到。
        let body = json!({
            "model_remains": [
                {
                    "model_name": "video",
                    "current_interval_remaining_percent": 50.0,
                    "current_weekly_remaining_percent": 50.0
                },
                {
                    "model_name": "general",
                    "current_interval_remaining_percent": 80.0,
                    "current_weekly_remaining_percent": 70.0,
                    "current_interval_status": 1,
                    "current_weekly_status": 1
                }
            ]
        });
        let tiers = parse_minimax_tiers(&body);
        assert_eq!(tiers.len(), 2);
        // 取的是 general 桶,不是 video(20%/30% 而非 50%/50%)
        assert_eq!(tiers[0].utilization, 20.0);
        assert_eq!(tiers[1].utilization, 30.0);
    }

    #[test]
    fn minimax_missing_general_returns_empty() {
        // model_remains 只有 video / 空 / 缺字段 → 不应崩溃,tiers 为空
        let body = json!({
            "model_remains": [
                {
                    "model_name": "video",
                    "current_interval_remaining_percent": 100.0,
                    "current_weekly_remaining_percent": 100.0
                }
            ]
        });
        assert!(parse_minimax_tiers(&body).is_empty());

        let body_empty: serde_json::Value = json!({ "model_remains": [] });
        assert!(parse_minimax_tiers(&body_empty).is_empty());

        let body_no_field = json!({});
        assert!(parse_minimax_tiers(&body_no_field).is_empty());
    }

    #[test]
    fn minimax_missing_percent_fields_skips_tier() {
        // 字段缺失时只跳过对应桶,另一边仍能展示
        let body = json!({
            "model_remains": [{
                "model_name": "general",
                "current_interval_remaining_percent": 60.0,
                "current_weekly_status": 1
                // 缺 current_weekly_remaining_percent
            }]
        });
        let tiers = parse_minimax_tiers(&body);
        assert_eq!(tiers.len(), 1);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 40.0);
    }

    #[test]
    fn minimax_weekly_status_3_skips_weekly_tier() {
        // 无周限额套餐:current_weekly_status=3,remaining_percent 恒为 100,
        // 不应推 weekly_limit tier(否则会显示"0% 已用"的假周桶)
        let body = json!({
            "model_remains": [
                {
                    "model_name": "general",
                    "start_time": 1_780_347_600_000_i64,
                    "end_time": 1_780_365_600_000_i64,
                    "remains_time": 4_161_372_i64,
                    "current_interval_remaining_percent": 99,
                    "current_interval_status": 1,
                    "current_weekly_total_count": 0,
                    "current_weekly_usage_count": 0,
                    "weekly_start_time": 1_780_243_200_000_i64,
                    "weekly_end_time": 1_780_848_000_000_i64,
                    "weekly_remains_time": 486_561_372_i64,
                    "current_weekly_status": 3,
                    "current_weekly_remaining_percent": 100
                },
                {
                    "model_name": "video",
                    "current_interval_remaining_percent": 100,
                    "current_weekly_status": 3,
                    "current_weekly_remaining_percent": 100
                }
            ],
            "base_resp": { "status_code": 0, "status_msg": "success" }
        });
        let tiers = parse_minimax_tiers(&body);
        assert_eq!(tiers.len(), 1);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 1.0);
        assert!(tiers[0].resets_at.is_some());
    }

    #[test]
    fn minimax_weekly_status_2_keeps_exhausted_weekly_tier() {
        // status=2:周额度已耗尽(实测 remaining_percent=0,官方控制台显示
        // 红条并按周限额限流),周桶照常展示成已用完,不能跳过
        let body = json!({
            "model_remains": [{
                "model_name": "general",
                "current_interval_remaining_percent": 80.0,
                "current_weekly_remaining_percent": 0.0,
                "current_weekly_status": 2
            }]
        });
        let tiers = parse_minimax_tiers(&body);
        assert_eq!(tiers.len(), 2);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(tiers[0].utilization, 20.0);
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(tiers[1].utilization, 100.0);
    }

    #[test]
    fn zhipu_quota_base_picks_endpoint_by_url() {
        for (case, base_url, expected) in [
            (
                "zhipu_quota_base_routes_bigmodel_url_to_cn_endpoint",
                "https://open.bigmodel.cn/api/paas/v4",
                "https://open.bigmodel.cn",
            ),
            (
                "zhipu_quota_base_routes_z_ai_url_to_en_endpoint",
                "https://api.z.ai/api/paas/v4",
                "https://api.z.ai",
            ),
            // 没有明显 Zhipu 域名特征时,默认走国际站(更通用的入口)
            (
                "zhipu_quota_base_defaults_to_en_for_unknown_url",
                "https://example.com/zhipu",
                "https://api.z.ai",
            ),
        ] {
            assert_eq!(zhipu_quota_base(base_url), expected, "{case}");
        }
    }

    #[test]
    fn zhipu_quota_base_routes_uppercase_cn_url_to_cn_endpoint() {
        // 大小写不敏感:与 detect_provider 保持一致的约定,避免大写 preset URL 静默路由到国际站
        assert_eq!(
            zhipu_quota_base("HTTPS://OPEN.BIGMODEL.CN/api/paas/v4"),
            "https://open.bigmodel.cn"
        );
        assert_eq!(
            zhipu_quota_base("https://Open.BigModel.cn/api/paas/v4"),
            "https://open.bigmodel.cn"
        );
    }

    // ── 火山方舟 Agent Plan / Coding Plan ──

    #[test]
    fn volcengine_afp_three_windows_from_official_example() {
        // 官方文档 GetAFPUsage 返回示例(逐字):5h 25% / weekly 30% / monthly
        // 42.525%;AFPDaily 被控制台隐藏,应跳过。
        let result = json!({
            "PlanType": "Large",
            "AFPFiveHour": { "Quota": 50.0,   "Used": 12.5,  "SubscribeTime": 1778788800000_i64, "ResetTime": 1778806800000_i64 },
            "AFPDaily":    { "Quota": 100.0,  "Used": 22.5,  "SubscribeTime": 1778716800000_i64, "ResetTime": 1778803200000_i64 },
            "AFPWeekly":   { "Quota": 500.0,  "Used": 150.0, "SubscribeTime": 1778457600000_i64, "ResetTime": 1779062400000_i64 },
            "AFPMonthly":  { "Quota": 2000.0, "Used": 850.5, "SubscribeTime": 1777939200000_i64, "ResetTime": 1780531200000_i64 }
        });
        let tiers = parse_afp_tiers(&result);
        assert_eq!(tiers.len(), 3, "daily 应被跳过,只剩 5h/周/月");
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert!((tiers[0].utilization - 25.0).abs() < 1e-9);
        assert!(tiers[0].resets_at.is_some());
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert!((tiers[1].utilization - 30.0).abs() < 1e-9);
        assert_eq!(tiers[2].name, TIER_MONTHLY);
        assert!((tiers[2].utilization - 42.525).abs() < 1e-9);
        assert!(tiers[2].resets_at.is_some());
    }

    #[test]
    fn volcengine_afp_zero_quota_windows_treated_as_unbound() {
        // 已鉴权但无 Agent Plan:窗口 Quota=0 → 空结果,调用方据此回落 Coding Plan。
        let result = json!({
            "PlanType": "",
            "AFPFiveHour": { "Quota": 0.0, "Used": 0.0 },
            "AFPWeekly":   { "Quota": 0.0, "Used": 0.0 },
            "AFPMonthly":  { "Quota": 0.0, "Used": 0.0 }
        });
        assert!(parse_afp_tiers(&result).is_empty());
    }

    #[test]
    fn volcengine_afp_partial_windows_only_subscribed_ones() {
        // 仅 5h 窗口有额度(缺周/月)→ 只产出一个 tier。
        let result = json!({
            "AFPFiveHour": { "Quota": 40.0, "Used": 10.0, "ResetTime": 1778806800000_i64 },
            "AFPWeekly":   { "Quota": 0.0,  "Used": 0.0 }
        });
        let tiers = parse_afp_tiers(&result);
        assert_eq!(tiers.len(), 1);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert!((tiers[0].utilization - 25.0).abs() < 1e-9);
    }

    #[test]
    fn volcengine_coding_plan_real_response_levels() {
        // 真实 GetCodingPlanUsage 响应(用户实测 2026-06-21):字段名是 `Level`(非 `Type`),
        // 仅百分比,秒级 ResetTimestamp;session 无活跃窗口回 -1 → 无重置时间。
        let result = json!({
            "Status": "Running",
            "UpdateTimestamp": 1782053286_i64,
            "QuotaUsage": [
                { "Level": "session", "Percent": 0.0,      "ResetTimestamp": -1_i64 },
                { "Level": "weekly",  "Percent": 1.672568, "ResetTimestamp": 1782057600_i64 },
                { "Level": "monthly", "Percent": 0.836284, "ResetTimestamp": 1784303999_i64 }
            ]
        });
        let tiers = parse_coding_plan_tiers(&result);
        assert_eq!(tiers.len(), 3);
        assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
        assert!((tiers[0].utilization - 0.0).abs() < 1e-9);
        assert!(
            tiers[0].resets_at.is_none(),
            "session ResetTimestamp=-1 应无重置时间"
        );
        assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
        assert!((tiers[1].utilization - 1.672568).abs() < 1e-6);
        assert!(tiers[1].resets_at.is_some());
        assert_eq!(tiers[2].name, TIER_MONTHLY);
        assert!((tiers[2].utilization - 0.836284).abs() < 1e-6);
    }

    #[test]
    fn volcengine_coding_plan_unknown_window_skipped_and_missing_array_empty() {
        let result = json!({
            "QuotaUsage": [
                { "Level": "daily", "Percent": 9.0 },
                { "Level": "weekly", "Percent": 20.0 }
            ]
        });
        let tiers = parse_coding_plan_tiers(&result);
        assert_eq!(tiers.len(), 1, "未知 daily 窗口跳过");
        assert_eq!(tiers[0].name, TIER_WEEKLY_LIMIT);

        assert!(parse_coding_plan_tiers(&json!({})).is_empty());
    }

    #[test]
    fn volcengine_region_derivation() {
        assert_eq!(
            volcengine_region("https://ark.cn-beijing.volces.com/api/coding"),
            "cn-beijing"
        );
        // 其他 region 的数据面域名按段提取。
        assert_eq!(
            volcengine_region("https://ark.cn-shanghai.volces.com/api/coding/v3"),
            "cn-shanghai"
        );
        // 无可识别 region 段时回落默认 cn-beijing。
        assert_eq!(
            volcengine_region("https://example.com/api/coding"),
            "cn-beijing"
        );
    }

    #[test]
    fn volcengine_canonical_query_is_sorted_and_encoded() {
        // 按 key 字母序:Action < Region < Version;值含 `-` 属 unreserved,不编码。
        assert_eq!(
            volcengine_canonical_query("GetAFPUsage", "cn-beijing"),
            "Action=GetAFPUsage&Region=cn-beijing&Version=2024-01-01"
        );
    }

    #[test]
    fn volcengine_sign_structure_and_determinism() {
        // 没有服务端金标准向量时,锁定签名的结构契约 + 确定性(足以抓住 header 顺序、
        // scope 后缀、algorithm 前缀、空 body hash 等实现错误)。真实正确性靠用户实测。
        let now = chrono::DateTime::parse_from_rfc3339("2024-06-21T00:00:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let region = "cn-beijing";
        let query = volcengine_canonical_query("GetAFPUsage", region);
        let (auth, x_date, x_content) =
            volcengine_sign("AKLTtest", "secretkey", region, &query, b"", now);

        // 空 body 的 SHA-256(固定值),证明走的是空 body。
        assert_eq!(
            x_content,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
        // X-Date 形如 20240621T000000Z。
        assert_eq!(x_date, "20240621T000000Z");
        // Authorization 结构:算法无 AWS4 前缀、scope 结尾 ark/request、固定 SignedHeaders。
        assert!(
            auth.starts_with("HMAC-SHA256 Credential=AKLTtest/20240621/cn-beijing/ark/request,"),
            "unexpected credential/scope: {auth}"
        );
        assert!(
            auth.contains("SignedHeaders=host;x-date;x-content-sha256;content-type,"),
            "unexpected signed headers: {auth}"
        );
        // Signature 是 64 位十六进制。
        let sig = auth.rsplit("Signature=").next().unwrap();
        assert_eq!(sig.len(), 64);
        assert!(sig.bytes().all(|b| b.is_ascii_hexdigit()));

        // 确定性:同输入同输出。
        let (auth2, _, _) = volcengine_sign("AKLTtest", "secretkey", region, &query, b"", now);
        assert_eq!(auth, auth2);
    }

    #[test]
    fn volcengine_auth_error_code_detection_and_extraction() {
        assert!(volcengine_is_auth_error_code("AccessDenied"));
        assert!(volcengine_is_auth_error_code("SignatureDoesNotMatch"));
        assert!(volcengine_is_auth_error_code("InvalidAuthorization"));
        assert!(volcengine_is_auth_error_code("Unauthorized"));
        assert!(!volcengine_is_auth_error_code("InvalidParameter.Action"));
        assert!(!volcengine_is_auth_error_code("InternalError"));

        // ResponseMetadata.Error 抽取
        let body = json!({
            "ResponseMetadata": { "RequestId": "x", "Error": { "Code": "AccessDenied", "Message": "no permission" } }
        });
        let (code, msg) = volcengine_response_error(&body).expect("应抽到 Error");
        assert_eq!(code, "AccessDenied");
        assert_eq!(msg, "no permission");

        // 无 Error 时返回 None
        let ok_body = json!({ "ResponseMetadata": { "RequestId": "x" }, "Result": {} });
        assert!(volcengine_response_error(&ok_body).is_none());
    }

    // ── 传输层错误通道语义:瞬时 → Err(前端 reject/retry),确定性 → Ok(success:false) ──
    //
    // ZenMux 直接请求 base_url,用本地 listener 驱动它的真实 HTTP
    // 路径,锁定 send 失败 / 读体中断 / 4xx / 非法 JSON 各自落在哪条通道。
    // balance / subscription 服务与本文件共用同一折叠模式,这里的用例同时充当
    // 三个服务的语义回归锚。

    use super::{get_coding_plan_quota, query_zenmux};
    use std::io::{Read, Write};

    /// 测试进程内可能有其他用例临时 set_var HTTP_PROXY(http_client 的
    /// loopback 检测测试),NO_PROXY 保证本地回环请求始终直连。
    fn ensure_no_proxy_for_loopback() {
        static ONCE: std::sync::Once = std::sync::Once::new();
        ONCE.call_once(|| {
            std::env::set_var("NO_PROXY", "127.0.0.1,localhost");
            std::env::set_var("no_proxy", "127.0.0.1,localhost");
        });
    }

    /// 起一个只服务一次连接的本地 HTTP server。`response=None` 表示读完请求
    /// 直接断开(模拟响应前连接中断)。返回它的 base_url。
    fn spawn_once_server(response: Option<String>) -> (String, std::thread::JoinHandle<()>) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind local listener");
        let port = listener.local_addr().expect("local addr").port();
        let handle = std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = [0u8; 2048];
                let _ = stream.read(&mut buf);
                if let Some(resp) = response {
                    let _ = stream.write_all(resp.as_bytes());
                    let _ = stream.flush();
                }
            }
        });
        (format!("http://127.0.0.1:{port}"), handle)
    }

    fn http_response(status_line: &str, body: &str) -> String {
        format!(
            "HTTP/1.1 {status_line}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
            body.len()
        )
    }

    /// 起一个本地 HTTP server,按顺序返回 responses,并记录每次请求的 path。
    fn spawn_sequence_server(
        responses: Vec<Option<String>>,
    ) -> (
        String,
        std::sync::Arc<std::sync::Mutex<Vec<String>>>,
        std::thread::JoinHandle<()>,
    ) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind local listener");
        let port = listener.local_addr().expect("local addr").port();
        let captured_paths = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let captured_paths_clone = captured_paths.clone();
        let handle = std::thread::spawn(move || {
            for response in responses {
                if let Ok((mut stream, _)) = listener.accept() {
                    let mut buf = [0u8; 2048];
                    let _ = stream.read(&mut buf);
                    let text = String::from_utf8_lossy(&buf).to_string();
                    let path = text
                        .lines()
                        .next()
                        .and_then(|line| line.split_whitespace().nth(1))
                        .map(|path| path.to_string())
                        .unwrap_or_default();
                    captured_paths_clone.lock().unwrap().push(path);
                    if let Some(response) = response {
                        let _ = stream.write_all(response.as_bytes());
                        let _ = stream.flush();
                    }
                }
            }
        });
        (format!("http://127.0.0.1:{port}"), captured_paths, handle)
    }

    #[tokio::test]
    async fn transient_connection_refused_returns_err() {
        ensure_no_proxy_for_loopback();
        // 绑定后立刻释放端口 → 连接被拒(send 失败)
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
        let port = listener.local_addr().expect("local addr").port();
        drop(listener);

        let result = query_zenmux(&format!("http://127.0.0.1:{port}"), "k").await;
        let err = result.expect_err("send 失败必须走 Err 通道(瞬时,前端 reject 后重试)");
        assert!(err.contains("Network error"), "err={err}");
    }

    #[tokio::test]
    async fn transient_connection_closed_before_response_returns_err() {
        ensure_no_proxy_for_loopback();
        let (base_url, handle) = spawn_once_server(None);

        let result = query_zenmux(&base_url, "k").await;
        let err = result.expect_err("响应前连接中断必须走 Err 通道(瞬时)");
        assert!(err.contains("Network error"), "err={err}");
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn transient_truncated_body_returns_err() {
        ensure_no_proxy_for_loopback();
        // 声明 content-length: 100 但只写一小段就断开 → 读体中断。
        // 锁定 bytes() 先于解析:这类失败必须走 Err(瞬时),不能因 reqwest 把
        // 读体错误包成 decode 而被误判成确定性的 "Failed to parse response"。
        let (base_url, handle) = spawn_once_server(Some(
            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 100\r\n\r\npartial"
                .to_string(),
        ));

        let result = query_zenmux(&base_url, "k").await;
        let err = result.expect_err("读体中断必须走 Err 通道(瞬时,前端 reject 后重试)");
        assert!(err.contains("Failed to read response"), "err={err}");
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn deterministic_http_401_stays_ok_with_auth_error() {
        ensure_no_proxy_for_loopback();
        let (base_url, handle) = spawn_once_server(Some(http_response("401 Unauthorized", "{}")));

        let quota = query_zenmux(&base_url, "k")
            .await
            .expect("鉴权失败是确定性失败,必须保持 Ok(success:false) 展示文案");
        assert!(!quota.success);
        assert!(matches!(quota.credential_status, CredentialStatus::Expired));
        let err = quota.error.expect("应有错误文案");
        assert!(err.contains("Authentication failed (HTTP 401"), "err={err}");
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn deterministic_http_429_stays_ok_with_status_in_error() {
        ensure_no_proxy_for_loopback();
        let (base_url, handle) =
            spawn_once_server(Some(http_response("429 Too Many Requests", "slow down")));

        let quota = query_zenmux(&base_url, "k")
            .await
            .expect("非 2xx 保持 Ok(success:false),状态码留在文案里交前端分类");
        assert!(!quota.success);
        // 前端 isTransientUsageError 靠 /http\s+(\d{3})/ 提取状态码把 429 归瞬时,
        // 文案格式是跨层契约,勿改。
        let err = quota.error.expect("应有错误文案");
        assert!(err.contains("HTTP 429"), "err={err}");
        handle.join().expect("server thread");
    }

    #[tokio::test]
    async fn deterministic_invalid_json_body_stays_ok_with_parse_error() {
        ensure_no_proxy_for_loopback();
        // 完整读到响应体但不是 JSON → is_decode → 确定性解析失败
        let (base_url, handle) = spawn_once_server(Some(http_response("200 OK", "not-json")));

        let quota = query_zenmux(&base_url, "k")
            .await
            .expect("完整但非法的响应体是确定性失败,必须保持 Ok(success:false)");
        assert!(!quota.success);
        let err = quota.error.expect("应有错误文案");
        assert!(err.contains("Failed to parse response"), "err={err}");
        handle.join().expect("server thread");
    }

    // ── 智谱团队套餐(Team Plan)──

    /// 起一个只服务一次连接的本地 HTTP server,捕获原始请求文本(请求行 + 头),
    /// 用于断言 team 查询发出的 URL query 与组织/项目请求头。`response=None` 时只捕获不回包。
    fn spawn_request_capturing_server(
        response: Option<String>,
    ) -> (
        String,
        std::sync::Arc<std::sync::Mutex<Option<String>>>,
        std::thread::JoinHandle<()>,
    ) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind local listener");
        let port = listener.local_addr().expect("local addr").port();
        let captured = std::sync::Arc::new(std::sync::Mutex::new(None::<String>));
        let captured_clone = captured.clone();
        let handle = std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf: Vec<u8> = Vec::new();
                let mut tmp = [0u8; 4096];
                // GET 无 body,读到 header 末尾(\r\n\r\n)即可
                while !buf.windows(4).any(|w| w == b"\r\n\r\n") {
                    match stream.read(&mut tmp) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => {
                            buf.extend_from_slice(&tmp[..n]);
                            if buf.len() > 16 * 1024 {
                                break;
                            }
                        }
                    }
                }
                *captured_clone.lock().unwrap() = Some(String::from_utf8_lossy(&buf).into_owned());
                if let Some(resp) = response {
                    let _ = stream.write_all(resp.as_bytes());
                    let _ = stream.flush();
                }
            }
        });
        (format!("http://127.0.0.1:{port}/team"), captured, handle)
    }

    #[tokio::test]
    async fn zhipu_team_missing_creds_returns_not_found() {
        // 团队版必需 api_key + 组织 ID + 项目 ID,缺任一在触网前返回 NotFound(不联网)。
        let cases: [(&str, Option<&str>, Option<&str>); 3] = [
            ("key", Some("org"), None),        // 缺 project
            ("key", None, Some("proj")),       // 缺 organization
            ("  ", Some("org"), Some("proj")), // 空 api_key
        ];
        for (api_key, org, project) in cases {
            let q = get_coding_plan_quota(
                "https://open.bigmodel.cn/api/coding",
                api_key,
                None,
                None,
                Some("zhipu_team"),
                org,
                project,
            )
            .await
            .expect("凭据缺失是确定性失败,保持 Ok(success:false)");
            assert!(!q.success, "应失败: api_key={api_key:?}");
            assert!(
                matches!(q.credential_status, CredentialStatus::NotFound),
                "应为 NotFound: api_key={api_key:?}"
            );
        }

        // 标识大小写不敏感(eq_ignore_ascii_case),大写仍命中 team 分支并返回引导文案。
        let msg = get_coding_plan_quota(
            "https://open.bigmodel.cn/api/coding",
            "key",
            None,
            None,
            Some("Zhipu_Team"),
            None,
            None,
        )
        .await
        .expect("ok")
        .error
        .expect("应有错误文案");
        assert!(
            msg.contains("API key + organization ID + project ID"),
            "err={msg}"
        );
    }

    #[tokio::test]
    async fn zhipu_team_request_carries_type2_and_org_project_headers() {
        ensure_no_proxy_for_loopback();
        // 响应 shape 与个人版一致:两条 TOKENS_LIMIT(unit 3/6)→ five_hour + weekly。
        let body = serde_json::json!({
            "success": true,
            "data": {
                "level": "max",
                "limits": [
                    { "type": "TOKENS_LIMIT", "unit": 3, "number": 5, "percentage": 26.0 },
                    { "type": "TOKENS_LIMIT", "unit": 6, "number": 1, "percentage": 5.0 }
                ]
            }
        });
        let body_str = body.to_string();
        let resp = format!(
            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body_str}",
            body_str.len()
        );
        let (base, captured, handle) = spawn_request_capturing_server(Some(resp));

        let quota = query_zhipu_team_at(&base, "team-key", "org-xxx", "proj_xxx")
            .await
            .expect("2xx + 合法 body 应成功");
        handle.join().expect("server thread");

        // 请求形状契约(与 token-monitor zaiTeamLimits 对齐):
        // 同路径加 ?type=2 + bigmodel-organization / bigmodel-project 头 + 鉴权头。
        // reqwest/hyper 发头会小写化,故整体转小写做包含匹配。
        let raw = captured.lock().unwrap().clone().expect("应捕获到请求");
        let raw_lc = raw.to_lowercase();
        assert!(raw_lc.contains("/team?type=2"), "缺 ?type=2: {raw}");
        assert!(
            raw_lc.contains("bigmodel-organization: org-xxx"),
            "缺组织头: {raw}"
        );
        assert!(
            raw_lc.contains("bigmodel-project: proj_xxx"),
            "缺项目头: {raw}"
        );
        assert!(
            raw_lc.contains("authorization: team-key"),
            "缺鉴权头: {raw}"
        );

        // 解析复用个人版 zhipu_quota_from_body / parse_zhipu_token_tiers。
        assert!(quota.success);
        assert_eq!(quota.tiers.len(), 2);
        assert_eq!(quota.tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(quota.tiers[0].utilization, 26.0);
        assert_eq!(quota.tiers[1].name, TIER_WEEKLY_LIMIT);
        assert_eq!(quota.tiers[1].utilization, 5.0);
    }

    // ── 智谱个人版:没有套餐单独返回,交给用量入口改查余额(#8465)──

    /// 2026-10-18 国内站无套餐按量 Key 实测原文。
    const ZHIPU_NO_PLAN_BODY: &str =
        r#"{"code":500,"msg":"当前用户不存在coding plan","success":false}"#;

    #[test]
    fn zhipu_no_plan_body_is_told_apart_from_other_errors() {
        let no_plan: serde_json::Value = serde_json::from_str(ZHIPU_NO_PLAN_BODY).unwrap();
        match zhipu_outcome_from_body(&no_plan) {
            CodingPlanOutcome::ZhipuNoPlan(quota) => {
                // 不回落的调用方(弹窗测试)拿到的仍是原来的失败文案
                assert!(!quota.success);
                assert!(quota.error.unwrap().contains("coding plan"));
            }
            CodingPlanOutcome::Quota(_) => panic!("无套餐应单独返回"),
        }

        for body in [
            json!({ "code": 500, "msg": "The current user does not have a coding plan", "success": false }),
            json!({ "code": 500, "msg": "Coding Plan not exist", "success": false }),
        ] {
            assert!(
                matches!(
                    zhipu_outcome_from_body(&body),
                    CodingPlanOutcome::ZhipuNoPlan(_)
                ),
                "{body}"
            );
        }

        // 其他业务错误、提到套餐但不是「没有」、success 不是 false 都不算没套餐
        for body in [
            json!({ "code": 1001, "msg": "令牌已过期或验证不正确", "success": false }),
            json!({ "code": 500, "msg": "coding plan 查询超时", "success": false }),
            json!({ "code": 500, "msg": "当前用户不存在coding plan" }),
            json!({ "success": true, "data": { "limits": [] } }),
        ] {
            assert!(
                matches!(zhipu_outcome_from_body(&body), CodingPlanOutcome::Quota(_)),
                "{body}"
            );
        }
    }

    #[tokio::test]
    async fn zhipu_personal_query_routes_plan_no_plan_and_auth_failure() {
        ensure_no_proxy_for_loopback();

        // 有套餐 → 套餐档位
        let plan_body = json!({
            "success": true,
            "data": {
                "level": "pro",
                "limits": [{ "type": "TOKENS_LIMIT", "unit": 3, "number": 5, "percentage": 12.0 }]
            }
        })
        .to_string();
        let (base, handle) = spawn_once_server(Some(http_response("200 OK", &plan_body)));
        let outcome = query_zhipu_at(&base, "key").await.expect("ok");
        handle.join().unwrap();
        let CodingPlanOutcome::Quota(quota) = outcome else {
            panic!("有套餐不应回落余额");
        };
        assert!(quota.success);
        assert_eq!(quota.tiers[0].name, TIER_FIVE_HOUR);
        assert_eq!(quota.tiers[0].utilization, 12.0);

        // 没有套餐(HTTP 200 + 业务错误)→ ZhipuNoPlan
        let (base, handle) = spawn_once_server(Some(http_response("200 OK", ZHIPU_NO_PLAN_BODY)));
        let outcome = query_zhipu_at(&base, "key").await.expect("ok");
        handle.join().unwrap();
        assert!(matches!(outcome, CodingPlanOutcome::ZhipuNoPlan(_)));

        // Key 无效 → 仍报鉴权失败,不回落余额
        let (base, handle) = spawn_once_server(Some(http_response(
            "401 Unauthorized",
            r#"{"error":{"code":"1000","message":"身份验证失败。"}}"#,
        )));
        let outcome = query_zhipu_at(&base, "bad").await.expect("ok");
        handle.join().unwrap();
        let CodingPlanOutcome::Quota(quota) = outcome else {
            panic!("鉴权失败不应回落余额");
        };
        assert!(!quota.success);
        assert!(matches!(quota.credential_status, CredentialStatus::Expired));
        assert!(quota.error.unwrap().contains("Authentication failed"));
    }

    /// 套餐地址按 host 认(含子域、端口、末尾的点),有路径要求的再看紧跟的路径;
    /// 中转站路径或查询串里出现的套餐域名不算。
    #[test]
    fn coding_plan_is_detected_by_host_and_path() {
        for (url, expected) in [
            ("https://api.kimi.com/coding/v1", Some("kimi")),
            ("https://api.kimi.com:443/coding/v1", Some("kimi")),
            ("https://api.kimi.com./coding/v1", Some("kimi")),
            ("https://api.kimi.com/v1", None),
            ("https://relay.example.com/api.kimi.com/coding/v1", None),
            ("https://www.bigmodel.cn/api/anthropic", Some("zhipu")),
            (
                "https://relay.example.com/v1?upstream=https://open.bigmodel.cn",
                None,
            ),
            ("https://api.z.ai.relay.example.com/api/anthropic", None),
            ("https://zenmux.ai/api/anthropic", Some("zenmux")),
            ("https://zenmux.example.com/api", None),
            ("https://opencode.ai:8443/zen/go/v1", Some("opencode_go")),
            ("https://relay.example.com/opencode.ai/zen/go/v1", None),
            (
                "https://api.commandcode.ai/provider?x=1",
                Some("command_code"),
            ),
            (
                "https://relay.example.com/api.commandcode.ai/provider",
                None,
            ),
            (
                "https://ark.cn-beijing.volces.com./api/plan/v3",
                Some("volcengine"),
            ),
            (
                "https://relay.example.com/ark.cn-beijing.volces.com/api/coding",
                None,
            ),
        ] {
            assert_eq!(detect_provider_id(url), expected, "{url}");
        }
        assert_eq!(
            zhipu_quota_base("https://relay.example.com/open.bigmodel.cn/api"),
            "https://api.z.ai"
        );
    }
}