export type DesktopAppInfo = {
  name: string;
  version: string;
  packageName: string;
};

export type DesktopAthenaHealth = {
  baseUrl: string;
  endpoint: string;
  statusCode: number;
  ok: boolean;
};

export const LOCAL_DESKTOP_ATHENA_BASE_URL = "http://127.0.0.1:5052";

export function isDesktopRuntime(): boolean {
  if (typeof window === "undefined") {
    return false;
  }

  return "__TAURI_INTERNALS__" in window || "__TAURI__" in window;
}

export async function desktopPing(): Promise<string | null> {
  if (!isDesktopRuntime()) {
    return null;
  }

  const { invoke } = await import("@tauri-apps/api/core");

  try {
    return await invoke<string>("ping");
  } catch {
    return null;
  }
}

export async function desktopAppInfo(): Promise<DesktopAppInfo | null> {
  if (!isDesktopRuntime()) {
    return null;
  }

  const { invoke } = await import("@tauri-apps/api/core");

  try {
    return await invoke<DesktopAppInfo>("app_info");
  } catch {
    return null;
  }
}

export async function desktopAthenaHealth(
  baseUrl: string,
): Promise<DesktopAthenaHealth | null> {
  if (!isDesktopRuntime()) {
    return null;
  }

  const { invoke } = await import("@tauri-apps/api/core");

  try {
    return await invoke<DesktopAthenaHealth>("athena_health", { baseUrl });
  } catch {
    return null;
  }
}

export async function bootstrapLocalApiKey(
  name?: string,
): Promise<string | null> {
  if (!isDesktopRuntime()) {
    return null;
  }

  const { invoke } = await import("@tauri-apps/api/core");

  try {
    return await invoke<string>("bootstrap_local_api_key", { name });
  } catch {
    return null;
  }
}

export async function restartLocalApi(): Promise<boolean> {
  if (!isDesktopRuntime()) {
    return false;
  }

  const { invoke } = await import("@tauri-apps/api/core");

  try {
    await invoke("restart_local_api");
    return true;
  } catch {
    return false;
  }
}
