"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var CustomModelWizard_exports = {};
__export(CustomModelWizard_exports, {
  default: () => CustomModelWizard_default
});
module.exports = __toCommonJS(CustomModelWizard_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_core = require("@dexto/core");
var import_provider_config = require("./custom-model-wizard/provider-config.js");
var import_shared = require("./custom-model-wizard/shared/index.js");
var import_LocalModelWizard = __toESM(require("./custom-model-wizard/LocalModelWizard.js"), 1);
const CustomModelWizard = (0, import_react.forwardRef)(
  function CustomModelWizard2({ isVisible, onComplete, onClose, initialModel }, ref) {
    const [selectedProvider, setSelectedProvider] = (0, import_react.useState)(null);
    const [providerIndex, setProviderIndex] = (0, import_react.useState)(0);
    const [currentStep, setCurrentStep] = (0, import_react.useState)(0);
    const [values, setValues] = (0, import_react.useState)({});
    const [currentInput, setCurrentInput] = (0, import_react.useState)("");
    const [error, setError] = (0, import_react.useState)(null);
    const [isSaving, setIsSaving] = (0, import_react.useState)(false);
    const [isValidating, setIsValidating] = (0, import_react.useState)(false);
    const [originalName, setOriginalName] = (0, import_react.useState)(null);
    const isEditing = initialModel !== null && initialModel !== void 0;
    const localModelWizardRef = (0, import_react.useRef)(null);
    const providerConfig = selectedProvider ? (0, import_provider_config.getProviderConfig)(selectedProvider) : null;
    const allWizardSteps = providerConfig?.steps ?? [];
    const getVisibleSteps = (0, import_react.useCallback)(
      (currentValues) => {
        return allWizardSteps.filter(
          (step) => !step.condition || step.condition(currentValues)
        );
      },
      [allWizardSteps]
    );
    const visibleSteps = getVisibleSteps(values);
    const currentStepConfig = visibleSteps[currentStep];
    (0, import_react.useEffect)(() => {
      if (isVisible) {
        if (initialModel) {
          const provider = initialModel.provider ?? "openai-compatible";
          const providers = (0, import_provider_config.getAvailableProviders)();
          setSelectedProvider(provider);
          setOriginalName(initialModel.name);
          setValues({
            name: initialModel.name,
            baseURL: initialModel.baseURL ?? "",
            displayName: initialModel.displayName ?? "",
            maxInputTokens: initialModel.maxInputTokens?.toString() ?? "",
            reasoningPreset: initialModel.reasoning?.variant ?? "",
            apiKey: initialModel.apiKey ?? "",
            filePath: initialModel.filePath ?? ""
          });
          setCurrentStep(0);
          setCurrentInput(initialModel.name);
          const idx = providers.indexOf(provider);
          setProviderIndex(idx >= 0 ? idx : 0);
        } else {
          setSelectedProvider(null);
          setOriginalName(null);
          setProviderIndex(0);
          setCurrentStep(0);
          setValues({});
          setCurrentInput("");
        }
        setError(null);
        setIsSaving(false);
        setIsValidating(false);
      }
    }, [isVisible, initialModel]);
    const handleProviderSelect = (0, import_react.useCallback)(() => {
      const provider = (0, import_provider_config.getProviderByMenuIndex)(providerIndex);
      if (provider) {
        setSelectedProvider(provider);
        setCurrentStep(0);
        setCurrentInput("");
        setError(null);
      }
    }, [providerIndex]);
    const handleNext = (0, import_react.useCallback)(async () => {
      if (!currentStepConfig || !selectedProvider || isSaving || isValidating) return;
      const value = currentInput.trim();
      if (currentStepConfig.validate) {
        const validationError = currentStepConfig.validate(value);
        if (validationError) {
          setError(validationError);
          return;
        }
      } else if (currentStepConfig.required && !value) {
        setError(`${currentStepConfig.label} is required`);
        return;
      }
      const asyncError = await (async () => {
        setIsValidating(true);
        setError(null);
        try {
          return await (0, import_provider_config.runAsyncValidation)(
            selectedProvider,
            currentStepConfig.field,
            value
          );
        } finally {
          setIsValidating(false);
        }
      })();
      if (asyncError) {
        setError(asyncError);
        return;
      }
      const newValues = { ...values, [currentStepConfig.field]: value };
      setValues(newValues);
      setError(null);
      setCurrentInput("");
      const updatedVisibleSteps = getVisibleSteps(newValues);
      if (currentStep >= updatedVisibleSteps.length - 1) {
        await saveModel(newValues);
      } else {
        const nextStep = currentStep + 1;
        setCurrentStep(nextStep);
        const nextStepConfig = updatedVisibleSteps[nextStep];
        const nextValue = nextStepConfig ? newValues[nextStepConfig.field] : void 0;
        setCurrentInput(nextValue ?? "");
      }
    }, [
      currentInput,
      currentStep,
      currentStepConfig,
      getVisibleSteps,
      isSaving,
      isValidating,
      selectedProvider,
      values
    ]);
    const saveModel = (0, import_react.useCallback)(
      async (finalValues) => {
        if (!selectedProvider || !providerConfig) return;
        const model = providerConfig.buildModel(finalValues, selectedProvider);
        const userEnteredKey = finalValues.apiKey?.trim();
        const providerKeyStatus = (0, import_agent_management.getProviderKeyStatus)(selectedProvider);
        const existingProviderKey = (0, import_agent_management.resolveApiKeyForProvider)(
          selectedProvider
        );
        const keyStorage = (0, import_agent_management.determineApiKeyStorage)(
          selectedProvider,
          userEnteredKey,
          providerKeyStatus.hasApiKey,
          existingProviderKey
        );
        if (keyStorage.saveToProviderEnvVar && userEnteredKey) {
          try {
            await (0, import_agent_management.saveProviderApiKey)(
              selectedProvider,
              userEnteredKey,
              process.cwd()
            );
          } catch (err) {
            import_core.logger.warn(
              `Failed to save provider API key: ${err instanceof Error ? err.message : "Unknown error"}`
            );
            keyStorage.saveAsPerModel = true;
          }
        }
        if (keyStorage.saveAsPerModel && userEnteredKey) {
          model.apiKey = userEnteredKey;
        }
        setIsSaving(true);
        try {
          if (originalName && originalName !== model.name) {
            try {
              await (0, import_agent_management.deleteCustomModel)(originalName);
            } catch (err) {
              import_core.logger.warn(
                `Failed to delete old model "${originalName}" during rename: ${err instanceof Error ? err.message : String(err)}`
              );
            }
          }
          await (0, import_agent_management.saveCustomModel)(model);
          onComplete(model);
        } catch (err) {
          import_core.logger.error(
            `Failed to save custom model: ${err instanceof Error ? err.message : "Unknown error"}`
          );
          setError(
            `Failed to save: ${err instanceof Error ? err.message : "Unknown error"}`
          );
          setIsSaving(false);
        }
      },
      [selectedProvider, providerConfig, originalName, onComplete]
    );
    const handleBack = (0, import_react.useCallback)(() => {
      if (currentStep > 0) {
        setCurrentStep(currentStep - 1);
        const prevStep = visibleSteps[currentStep - 1];
        if (prevStep) {
          setCurrentInput(values[prevStep.field] || "");
        }
        setError(null);
      } else if (selectedProvider) {
        setSelectedProvider(null);
        setError(null);
      } else {
        onClose();
      }
    }, [currentStep, onClose, selectedProvider, values, visibleSteps]);
    (0, import_react.useImperativeHandle)(
      ref,
      () => ({
        handleInput: (input, key) => {
          if (!isVisible || isSaving || isValidating) return false;
          if (selectedProvider === "local" && localModelWizardRef.current) {
            return localModelWizardRef.current.handleInput(input, key);
          }
          if (key.escape) {
            handleBack();
            return true;
          }
          if (!selectedProvider) {
            const providers = (0, import_provider_config.getAvailableProviders)();
            if (key.upArrow) {
              setProviderIndex(
                (prev) => prev > 0 ? prev - 1 : providers.length - 1
              );
              return true;
            }
            if (key.downArrow) {
              setProviderIndex(
                (prev) => prev < providers.length - 1 ? prev + 1 : 0
              );
              return true;
            }
            if (key.return) {
              handleProviderSelect();
              return true;
            }
            return true;
          }
          if (key.return) {
            void handleNext();
            return true;
          }
          if (key.backspace || key.delete) {
            setCurrentInput((prev) => prev.slice(0, -1));
            setError(null);
            return true;
          }
          if (input && !key.ctrl && !key.meta) {
            setCurrentInput((prev) => prev + input);
            setError(null);
            return true;
          }
          return false;
        }
      }),
      [
        isVisible,
        isSaving,
        isValidating,
        handleBack,
        handleNext,
        handleProviderSelect,
        selectedProvider
      ]
    );
    if (!isVisible) return null;
    if (!selectedProvider) {
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_shared.ProviderSelector, { selectedIndex: providerIndex, isEditing });
    }
    if (selectedProvider === "local") {
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_LocalModelWizard.default,
        {
          ref: localModelWizardRef,
          isVisible,
          onComplete,
          onClose: () => {
            setSelectedProvider(null);
          }
        }
      );
    }
    if (!currentStepConfig || !providerConfig) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
      import_ink.Box,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: "green",
        paddingX: 1,
        marginTop: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { bold: true, color: "green", children: isEditing ? "Edit Custom Model" : "Add Custom Model" }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
              " ",
              "(",
              providerConfig.displayName,
              ") Step ",
              currentStep + 1,
              "/",
              visibleSteps.length
            ] })
          ] }),
          providerConfig.setupInfo && currentStep === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_shared.SetupInfoBanner,
            {
              title: providerConfig.setupInfo.title,
              description: providerConfig.setupInfo.description,
              docsUrl: providerConfig.setupInfo.docsUrl
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_shared.WizardStepInput,
            {
              step: currentStepConfig,
              currentInput,
              error,
              isValidating,
              isSaving,
              additionalContent: currentStepConfig.field === "apiKey" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_shared.ApiKeyStep, { provider: selectedProvider }) : void 0
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
            "Enter to continue \u2022 Esc to",
            " ",
            currentStep > 0 ? "go back" : "back to provider"
          ] }) })
        ]
      }
    );
  }
);
var CustomModelWizard_default = CustomModelWizard;
