import { mkdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { buildWorkspaceEntryLobsterEnv } from "../../apps/desktop/src/main/services/workspace-entry-lobster-env.js";

function assert(condition: unknown, message: string): asserts condition {
  if (!condition) {
    throw new Error(message);
  }
}

function assertThrowsMissingKey(input: string | undefined): void {
  try {
    buildWorkspaceEntryLobsterEnv(input);
  } catch (error) {
    assert(error instanceof Error, "Missing-key path should throw an Error.");
    assert(error.message === "请先绑定龙虾密钥", "Missing-key error message changed.");
    return;
  }

  throw new Error("Missing-key path did not throw.");
}

async function main(): Promise<void> {
  const __filename = fileURLToPath(import.meta.url);
  const __dirname = path.dirname(__filename);
  const repoRoot = path.resolve(__dirname, "..", "..");
  const resultPath = path.resolve(process.argv[2] ?? path.join(repoRoot, ".tmp", "workspace-entry-lobster-env-smoke", "result.json"));
  const tempRoot = path.dirname(resultPath);

  await rm(tempRoot, { recursive: true, force: true });
  await mkdir(tempRoot, { recursive: true });

  const env = buildWorkspaceEntryLobsterEnv("  lobster-secret  ");
  assert(env.QJCLAW_LOBSTER_KEY === "lobster-secret", "Primary lobster env var should use the trimmed key.");
  assert(env.OPENCLAW_EMPLOYEE_API_KEY === "lobster-secret", "Compatibility env var should use the trimmed key.");
  assert(Object.keys(env).length === 2, "Workspace-entry lobster env should expose only the two expected variables.");

  assertThrowsMissingKey(undefined);
  assertThrowsMissingKey("");
  assertThrowsMissingKey("   ");

  await writeFile(resultPath, JSON.stringify({
    ok: true,
    envKeys: Object.keys(env)
  }, null, 2), "utf8");
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
