import os from "node:os";
import { afterEach, describe, expect, it, vi } from "vitest";
import { importFreshModule } from "../../test/helpers/import-fresh.js";

const execFileMock = vi.hoisted(() => vi.fn());

vi.mock("node:child_process", () => ({
  execFile: (...args: unknown[]) => execFileMock(...args),
}));

const originalVitest = process.env.VITEST;
const originalNodeEnv = process.env.NODE_ENV;

async function importMachineName(scope: string) {
  return await importFreshModule<typeof import("./machine-name.js")>(
    import.meta.url,
    `./machine-name.js?scope=${scope}`,
  );
}

afterEach(() => {
  execFileMock.mockReset();
  vi.restoreAllMocks();
  if (originalVitest === undefined) {
    delete process.env.VITEST;
  } else {
    process.env.VITEST = originalVitest;
  }
  if (originalNodeEnv === undefined) {
    delete process.env.NODE_ENV;
  } else {
    process.env.NODE_ENV = originalNodeEnv;
  }
});

describe("getMachineDisplayName", () => {
  it("uses the hostname fallback in test mode and strips a trimmed .local suffix", async () => {
    const hostnameSpy = vi.spyOn(os, "hostname").mockReturnValue("  clawbox.LOCAL  ");
    const machineName = await importMachineName("test-fallback");

    await expect(machineName.getMachineDisplayName()).resolves.toBe("clawbox");
    await expect(machineName.getMachineDisplayName()).resolves.toBe("clawbox");
    expect(hostnameSpy).toHaveBeenCalledTimes(1);
    expect(execFileMock).not.toHaveBeenCalled();
  });

  it("falls back to the default product name when hostname is blank", async () => {
    vi.spyOn(os, "hostname").mockReturnValue("   ");
    const machineName = await importMachineName("blank-hostname");

    await expect(machineName.getMachineDisplayName()).resolves.toBe("openclaw");
    expect(execFileMock).not.toHaveBeenCalled();
  });
});
