import { AppShell } from "@/components/AppShell";
import { ProvidersSettings } from "@/components/settings/ProvidersSettings";
import { PageHeader } from "@/components/ui/PageHeader";
import { fetchKimiOauthStatus, fetchProviders } from "@/lib/api/server";
import type { ProvidersResponse } from "@/lib/api/types";

// 模型与提供商设置（UX §6.10）。Server Component 取初始数据（含 Kimi Code OAuth 状态）。
export default async function ProvidersSettingsPage() {
  let initial: ProvidersResponse = { providers: [], tier_routing: [] };
  let kimiOauth = { connected: false, expiresAt: null as string | null };
  let loadError = false;
  try {
    const [providers, oauthStatus] = await Promise.all([
      fetchProviders(),
      fetchKimiOauthStatus(),
    ]);
    initial = providers;
    kimiOauth = {
      connected: oauthStatus.connected === true,
      expiresAt:
        typeof oauthStatus.expires_at === "string"
          ? oauthStatus.expires_at
          : null,
    };
  } catch {
    loadError = true;
  }

  return (
    <AppShell title="设置 › 模型与提供商">
      <div className="mx-auto max-w-6xl px-4 py-8 sm:px-8 sm:py-10">
        <PageHeader
          title="模型与提供商"
          description="配置写手、分析、轻量三类能力档位的路由，并管理 API Key 与 Kimi Code OAuth。"
        />
        {loadError ? (
          <p className="rounded border border-conflict bg-panel p-6 text-conflict">
            无法连接后端服务，请确认 API 已启动后刷新。
          </p>
        ) : (
          <ProvidersSettings initial={initial} kimiOauth={kimiOauth} />
        )}
      </div>
    </AppShell>
  );
}
