// Verifies generated talk default config stays aligned with schema.
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { FIELD_HELP } from "./schema.help.js";
import { describeTalkSilenceTimeoutDefaults } from "./talk-defaults.js";

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const EXPECTED_TALK_SILENCE_TIMEOUT_MS_BY_PLATFORM = {
  macos: 700,
  android: 700,
  ios: 900,
} as const;

function readRepoFile(relativePath: string): string {
  try {
    return fs.readFileSync(path.join(repoRoot, relativePath), "utf8");
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
      throw error;
    }
  }

  // Sparse worktrees may omit app sources, but the tracked blob is still the parity source.
  return execFileSync("git", ["show", `HEAD:${relativePath}`], {
    cwd: repoRoot,
    encoding: "utf8",
  });
}

describe("talk silence timeout defaults", () => {
  it("keeps help text and docs aligned with the policy", () => {
    const defaultsDescription = describeTalkSilenceTimeoutDefaults();
    const talkDocDefaults =
      `\`${EXPECTED_TALK_SILENCE_TIMEOUT_MS_BY_PLATFORM.macos}\` ms macOS/Android, ` +
      `\`${EXPECTED_TALK_SILENCE_TIMEOUT_MS_BY_PLATFORM.ios}\` ms iOS`;

    expect(FIELD_HELP["talk.silenceTimeoutMs"]).toContain(defaultsDescription);
    expect(readRepoFile("docs/gateway/config-agents.md")).toContain(defaultsDescription);
    expect(readRepoFile("docs/nodes/talk.md")).toContain(talkDocDefaults);
  });

  it("matches the Apple and Android runtime constants", () => {
    const macDefaults = readRepoFile("apps/macos/Sources/OpenClaw/TalkDefaults.swift");
    const iosDefaults = readRepoFile("apps/ios/Sources/Voice/TalkDefaults.swift");
    const androidDefaults = readRepoFile(
      "apps/android/app/src/main/java/ai/openclaw/app/voice/TalkDefaults.kt",
    );

    expect(macDefaults).toContain(
      `static let silenceTimeoutMs = ${EXPECTED_TALK_SILENCE_TIMEOUT_MS_BY_PLATFORM.macos}`,
    );
    expect(iosDefaults).toContain(
      `static let silenceTimeoutMs = ${EXPECTED_TALK_SILENCE_TIMEOUT_MS_BY_PLATFORM.ios}`,
    );
    expect(androidDefaults).toContain(
      `const val defaultSilenceTimeoutMs = ${EXPECTED_TALK_SILENCE_TIMEOUT_MS_BY_PLATFORM.android}L`,
    );
  });
});
