import { mkdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
  buildWorkspaceEntryLobsterEnv,
  buildWorkspaceEntryWorkspacePathEnv
} 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.");
}

function assertThrowsMissingWorkspacePath(input: string | undefined): void {
  try {
    buildWorkspaceEntryWorkspacePathEnv(input);
  } catch (error) {
    assert(error instanceof Error, "Missing-workspace-path path should throw an Error.");
    assert(error.message === "请先设置工作目录", "Missing-workspace-path error message changed.");
    return;
  }

  throw new Error("Missing-workspace-path 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.");

  const workspacePathEnv = buildWorkspaceEntryWorkspacePathEnv("  /tmp/qjc-workspace  ");
  assert(workspacePathEnv.QJCLAW_WORKSPACE_PATH === "/tmp/qjc-workspace", "Workspace path env var should use the trimmed path.");
  assert(Object.keys(workspacePathEnv).length === 1, "Workspace-entry workspace path env should expose only the expected variable.");

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

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

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