// @bun
import {
  resolveCommandContext
} from "./chunk-2jcqy5j6.js";
import {
  AdkError,
  exports_dependencies
} from "./chunk-7krp2mgz.js";

// src/utils/chat-preflight.ts
import { createInterface } from "readline/promises";
var CHAT_INTEGRATION_NAME = "chat";
async function ensureChatIntegrationReady(projectPath, _devId, options = {}) {
  let project = options.project;
  let client = options.client;
  if (!project || !client) {
    const context = await resolveCommandContext({
      cwd: projectPath,
      target: "dev",
      require: ["project", "credentials", "workspace", "bot"]
    });
    project ??= context.project;
    client ??= context.client;
  }
  if (!project || !client) {
    throw new AdkError({
      code: "CHAT_PREFLIGHT",
      message: "Unable to resolve project credentials for chat preflight.",
      expected: true
    });
  }
  const dm = await exports_dependencies.DependencyManager.fromProject({
    projectPath,
    env: "dev",
    client
  });
  const entries = await dm.list("integration");
  const existing = entries.find((entry) => isChatIntegrationName(entry.name));
  if (existing) {
    if (!existing.enabled) {
      await dm.enable("integration", existing.alias);
    }
    return { alias: existing.alias, addedToConfig: false, syncedToBot: !existing.enabled };
  }
  const promptForInstall = options.promptForInstall ?? promptToInstallChat;
  const shouldInstall = await promptForInstall("Chat integration is not declared in the lock. Install it now? (y/N) ");
  if (!shouldInstall) {
    throw new AdkError({
      code: "CHAT_PREFLIGHT",
      message: "Chat integration is required to run `adk chat`. Run `adk integrations add chat` or re-run this command and accept the install prompt.",
      expected: true
    });
  }
  const result = await dm.add("integration", { name: CHAT_INTEGRATION_NAME, version: "latest" });
  const alias = result.resource?.alias ?? CHAT_INTEGRATION_NAME;
  return { alias, addedToConfig: true, syncedToBot: true };
}
function isChatIntegrationName(name) {
  if (!name)
    return false;
  return name === CHAT_INTEGRATION_NAME || name.split("/").at(-1) === CHAT_INTEGRATION_NAME;
}
async function promptToInstallChat(message) {
  if (!process.stdin.isTTY) {
    throw new AdkError({
      code: "CHAT_PREFLIGHT",
      message: "Chat integration is missing from the lock and this terminal is not interactive. Run `adk integrations add chat` first, then retry `adk chat`.",
      expected: true
    });
  }
  const rl = createInterface({
    input: process.stdin,
    output: process.stderr
  });
  try {
    const answer = await rl.question(message);
    const normalized = answer.trim().toLowerCase();
    return normalized === "y" || normalized === "yes";
  } finally {
    rl.close();
  }
}

export { ensureChatIntegrationReady };
