"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var ApiKeyInput_exports = {};
__export(ApiKeyInput_exports, {
  default: () => ApiKeyInput_default
});
module.exports = __toCommonJS(ApiKeyInput_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_agent_management = require("@dexto/agent-management");
var import_host = require("../../host/index.js");
var import_host2 = require("../../host/index.js");
const ApiKeyInput = (0, import_react.forwardRef)(function ApiKeyInput2({ isVisible, provider, onSaved, onClose }, ref) {
  const [apiKey, setApiKey] = (0, import_react.useState)("");
  const [error, setError] = (0, import_react.useState)(null);
  const [isSaving, setIsSaving] = (0, import_react.useState)(false);
  (0, import_react.useEffect)(() => {
    if (isVisible) {
      setApiKey("");
      setError(null);
      setIsSaving(false);
    }
  }, [isVisible, provider]);
  const handleSubmit = (0, import_react.useCallback)(async () => {
    const trimmedKey = apiKey.trim();
    if (!trimmedKey) {
      setError("API key is required");
      return;
    }
    if (!(0, import_host2.isValidApiKeyFormat)(trimmedKey, provider)) {
      setError(`Invalid ${(0, import_host2.getProviderDisplayName)(provider)} API key format`);
      return;
    }
    setError(null);
    setIsSaving(true);
    try {
      const meta = await (0, import_agent_management.saveProviderApiKey)(provider, trimmedKey, process.cwd());
      await (0, import_host.applyLayeredEnvironmentLoading)();
      onSaved({ provider, envVar: meta.envVar });
    } catch (err) {
      setError(`Failed to save: ${err instanceof Error ? err.message : String(err)}`);
      setIsSaving(false);
    }
  }, [apiKey, provider, onSaved]);
  (0, import_react.useImperativeHandle)(
    ref,
    () => ({
      handleInput: (input, key) => {
        if (!isVisible || isSaving) return false;
        if (key.escape) {
          onClose();
          return true;
        }
        if (key.return) {
          void handleSubmit();
          return true;
        }
        if (key.backspace || key.delete) {
          setApiKey((prev) => prev.slice(0, -1));
          setError(null);
          return true;
        }
        if (input && !key.ctrl && !key.meta) {
          setApiKey((prev) => prev + input);
          setError(null);
          return true;
        }
        return false;
      }
    }),
    [isVisible, isSaving, onClose, handleSubmit]
  );
  if (!isVisible) return null;
  const providerName = (0, import_host2.getProviderDisplayName)(provider);
  const envVar = (0, import_agent_management.getPrimaryApiKeyEnvVar)(provider);
  const instructions = (0, import_host2.getProviderInstructions)(provider);
  const maskedKey = apiKey.length > 8 ? `${apiKey.slice(0, 4)}${"*".repeat(Math.min(apiKey.length - 8, 20))}${apiKey.slice(-4)}` : "*".repeat(apiKey.length);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
    import_ink.Box,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: "cyan",
      paddingX: 1,
      marginTop: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { bold: true, color: "cyan", children: [
          "API Key Required for ",
          providerName
        ] }) }),
        instructions && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: instructions.content }) }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "This key will be saved to " }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellowBright", children: envVar }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: " in your .env file" })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { bold: true, children: [
          "Enter your ",
          providerName,
          " API key:"
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", children: "> " }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: maskedKey }),
          !isSaving && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", children: "_" })
        ] }),
        isSaving && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellowBright", children: "Saving API key..." }) }),
        error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "red", children: error }) }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Enter to save \u2022 Esc to cancel" }) })
      ]
    }
  );
});
var ApiKeyInput_default = ApiKeyInput;
