import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
  MOONSHOT_BASE_URL as MOONSHOT_AI_BASE_URL,
  MOONSHOT_CN_BASE_URL,
} from "../commands/onboard-auth.models.js";
import { captureEnv } from "../test-utils/env.js";
import { resolveImplicitProviders } from "./models-config.providers.js";

describe("moonshot implicit provider (#33637)", () => {
  it("uses explicit CN baseUrl when provided", async () => {
    const agentDir = mkdtempSync(join(tmpdir(), "openclaw-test-"));
    const envSnapshot = captureEnv(["MOONSHOT_API_KEY"]);
    process.env.MOONSHOT_API_KEY = "sk-test-cn";

    try {
      const providers = await resolveImplicitProviders({
        agentDir,
        explicitProviders: {
          moonshot: {
            baseUrl: MOONSHOT_CN_BASE_URL,
            api: "openai-completions",
            models: [
              {
                id: "kimi-k2.5",
                name: "Kimi K2.5",
                reasoning: false,
                input: ["text", "image"],
                cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
                contextWindow: 256000,
                maxTokens: 8192,
              },
            ],
          },
        },
      });
      expect(providers?.moonshot).toBeDefined();
      expect(providers?.moonshot?.baseUrl).toBe(MOONSHOT_CN_BASE_URL);
      expect(providers?.moonshot?.apiKey).toBeDefined();
    } finally {
      envSnapshot.restore();
    }
  });

  it("defaults to .ai baseUrl when no explicit provider", async () => {
    const agentDir = mkdtempSync(join(tmpdir(), "openclaw-test-"));
    const envSnapshot = captureEnv(["MOONSHOT_API_KEY"]);
    process.env.MOONSHOT_API_KEY = "sk-test";

    try {
      const providers = await resolveImplicitProviders({ agentDir });
      expect(providers?.moonshot).toBeDefined();
      expect(providers?.moonshot?.baseUrl).toBe(MOONSHOT_AI_BASE_URL);
    } finally {
      envSnapshot.restore();
    }
  });
});
