import {
  detectModel
} from "./chunk-HHAJ3QF6.js";
import {
  detectBackend
} from "./chunk-HGAMIPFO.js";
import {
  getGlobalConfigPath
} from "./chunk-CQGTEGKL.js";

// src/cli/config.ts
import { z } from "zod";
import { randomUUID } from "crypto";
import { readFile, writeFile, mkdir, access } from "fs/promises";
import { dirname } from "path";
var SMART_DEFAULTS = ["http://localhost:8000", "http://localhost:11434", "http://localhost:8080"];
async function trySmartDefaults(_mode) {
  const results = await Promise.all(
    SMART_DEFAULTS.map(async (url) => {
      try {
        const [backend, model] = await Promise.all([
          detectBackend(url, void 0, true),
          detectModel(url, 1, true)
          // Only 1 retry attempt
        ]);
        if (backend !== "unknown" && model) {
          return { url, backend, model };
        }
      } catch {
      }
      return null;
    })
  );
  return results.find((r) => r !== null) || null;
}
async function configFileExists(mode) {
  const configPath = getGlobalConfigPath(mode);
  try {
    await access(configPath);
    return true;
  } catch {
    return false;
  }
}
var backendSchema = z.enum([
  "auto",
  "vllm",
  "sglang",
  "ollama",
  "llamacpp",
  "openai",
  "anthropic",
  "opencode-go",
  "unknown"
]);
var modelConfigSchema = z.object({
  id: z.string(),
  contextWindow: z.number(),
  source: z.enum(["backend", "user", "default"]),
  temperature: z.number().optional(),
  topP: z.number().optional(),
  topK: z.number().optional(),
  maxTokens: z.number().optional()
}).passthrough();
var providerSchema = z.object({
  id: z.string(),
  name: z.string(),
  url: z.string(),
  backend: backendSchema,
  apiKey: z.string().optional(),
  models: z.array(modelConfigSchema).default([]),
  isActive: z.boolean(),
  createdAt: z.string(),
  // Deprecated: model field kept for migration, will be removed after migration
  model: z.string().optional(),
  // Deprecated: maxContext kept for migration
  maxContext: z.number().optional()
});
var serverSchema = z.object({
  port: z.number().default(10369),
  host: z.string().default("127.0.0.1"),
  openBrowser: z.boolean().default(true)
});
var loggingSchema = z.object({
  level: z.enum(["debug", "info", "warn", "error"]).default("error")
});
var databaseSchema = z.object({
  path: z.string().default("")
});
var workspaceSchema = z.object({
  workdir: z.string().default(process.cwd())
});
var visionFallbackSchema = z.object({
  enabled: z.boolean().default(false),
  url: z.string().default("http://localhost:11434"),
  model: z.string().default("qwen3.5:0.8b"),
  timeout: z.number().default(120)
});
var defaultVisionFallback = { enabled: false, url: "http://localhost:11434", model: "qwen3.5:0.8b", timeout: 120 };
var configSchema = z.object({
  providers: z.array(providerSchema).default([]),
  defaultModelSelection: z.string().optional(),
  activeProviderId: z.string().optional(),
  activeWorkflowId: z.string().optional(),
  server: serverSchema.default({ port: 10369, host: "127.0.0.1", openBrowser: true }),
  logging: loggingSchema.default({ level: "error" }),
  database: databaseSchema.default({ path: "" }),
  workspace: workspaceSchema.default(() => ({ workdir: process.cwd() })),
  visionFallback: visionFallbackSchema.optional()
}).transform((data) => ({
  providers: data.providers ?? [],
  defaultModelSelection: data.defaultModelSelection,
  activeProviderId: data.activeProviderId,
  activeWorkflowId: data.activeWorkflowId,
  server: data.server ?? { port: 10369, host: "127.0.0.1", openBrowser: true },
  logging: data.logging ?? { level: "error" },
  database: data.database ?? { path: "" },
  workspace: data.workspace ?? { workdir: process.cwd() },
  visionFallback: data.visionFallback ?? defaultVisionFallback
}));
var oldLlmSchema = z.object({
  url: z.string().url().default("http://localhost:8000/v1"),
  model: z.string().default("auto"),
  backend: z.enum(["auto", "vllm", "sglang", "ollama", "llamacpp"]).default("auto"),
  maxContext: z.number().default(2e5),
  disableThinking: z.boolean().default(false),
  apiKey: z.string().optional()
});
var oldConfigSchema = z.object({
  llm: oldLlmSchema,
  server: serverSchema.default({ port: 10369, host: "127.0.0.1", openBrowser: true }),
  logging: loggingSchema.default({ level: "error" }),
  database: databaseSchema.default({ path: "" })
});
function getVisionFallback(config) {
  return config.visionFallback ?? getDefaultVisionFallback();
}
function migrateConfig(raw) {
  if (typeof raw === "object" && raw !== null && "providers" in raw) {
    const obj = raw;
    let migrationOccurred = false;
    const providers = obj.providers.map((p) => {
      const { model, maxContext, models: existingModels, ...rest } = p;
      let models = existingModels ?? [];
      if (maxContext !== void 0 && (existingModels === void 0 || existingModels.length === 0)) {
        migrationOccurred = true;
        models = [
          {
            id: model ?? "auto",
            contextWindow: maxContext,
            source: "user"
          }
        ];
      }
      return {
        ...rest,
        models
      };
    });
    if (migrationOccurred) {
      console.warn("Migrating legacy maxContext to model-specific config");
    }
    if (obj.defaultModelSelection) {
      return {
        config: configSchema.parse({
          ...obj,
          providers
        }),
        migrated: migrationOccurred
      };
    }
    let defaultModelSelection;
    if (obj.activeProviderId) {
      const activeProvider = obj.providers.find((p) => p.id === obj.activeProviderId);
      if (activeProvider?.model) {
        defaultModelSelection = `${obj.activeProviderId}/${activeProvider.model}`;
      } else {
        defaultModelSelection = `${obj.activeProviderId}/auto`;
      }
    }
    return {
      config: configSchema.parse({
        ...obj,
        providers,
        defaultModelSelection
      }),
      migrated: migrationOccurred
    };
  }
  if (typeof raw === "object" && raw !== null && "llm" in raw) {
    const oldConfig = oldConfigSchema.parse(raw);
    const providerId = randomUUID();
    const models = [
      {
        id: oldConfig.llm.model || "auto",
        contextWindow: oldConfig.llm.maxContext,
        source: "user"
      }
    ];
    const provider = {
      id: providerId,
      name: "Default",
      url: oldConfig.llm.url,
      backend: oldConfig.llm.backend,
      apiKey: oldConfig.llm.apiKey,
      models,
      isActive: true,
      createdAt: (/* @__PURE__ */ new Date()).toISOString()
    };
    const model = oldConfig.llm.model || "auto";
    return {
      config: configSchema.parse({
        providers: [provider],
        defaultModelSelection: `${providerId}/${model}`,
        server: oldConfig.server,
        logging: oldConfig.logging,
        database: oldConfig.database,
        workspace: { workdir: process.cwd() }
      }),
      migrated: true
    };
  }
  return {
    config: configSchema.parse(raw),
    migrated: false
  };
}
async function loadGlobalConfig(mode) {
  const configPath = getGlobalConfigPath(mode);
  try {
    const content = await readFile(configPath, "utf-8");
    const parsed = JSON.parse(content);
    const { config, migrated } = migrateConfig(parsed);
    if (migrated) {
      await saveGlobalConfig(mode, config);
    }
    return config;
  } catch {
    return configSchema.parse({});
  }
}
function getDefaultVisionFallback() {
  return { enabled: false, url: "http://localhost:11434", model: "qwen3.5:0.8b", timeout: 120 };
}
async function saveGlobalConfig(mode, config) {
  const configPath = getGlobalConfigPath(mode);
  const fullConfig = {
    providers: config.providers ?? [],
    defaultModelSelection: config.defaultModelSelection,
    activeProviderId: config.activeProviderId,
    activeWorkflowId: config.activeWorkflowId,
    server: config.server ?? { port: 10369, host: "127.0.0.1", openBrowser: true },
    logging: config.logging ?? { level: "error" },
    database: config.database ?? { path: "" },
    workspace: config.workspace ?? { workdir: process.cwd() },
    visionFallback: config.visionFallback ?? {
      enabled: false,
      url: "http://localhost:11434",
      model: "qwen3.5:0.8b",
      timeout: 120
    }
  };
  await mkdir(dirname(configPath), { recursive: true });
  await writeFile(configPath, JSON.stringify(fullConfig, null, 2));
}
function getActiveProvider(config) {
  if (config.defaultModelSelection) {
    const slashIndex = config.defaultModelSelection.indexOf("/");
    const providerId = slashIndex === -1 ? config.defaultModelSelection : config.defaultModelSelection.substring(0, slashIndex);
    return config.providers?.find((p) => p.id === providerId);
  }
  if (!config.activeProviderId) return void 0;
  return config.providers?.find((p) => p.id === config.activeProviderId);
}
function getDefaultModel(config) {
  if (!config.defaultModelSelection) return void 0;
  const slashIndex = config.defaultModelSelection.indexOf("/");
  return slashIndex === -1 ? "auto" : config.defaultModelSelection.substring(slashIndex + 1);
}
function setDefaultModelSelection(config, providerId, model) {
  const defaultModelSelection = `${providerId}/${model}`;
  return {
    providers: config.providers?.map((p) => ({ ...p, isActive: p.id === providerId })) ?? [],
    defaultModelSelection,
    activeProviderId: providerId,
    activeWorkflowId: config.activeWorkflowId,
    server: config.server ?? { port: 10369, host: "127.0.0.1", openBrowser: true },
    logging: config.logging ?? { level: "error" },
    database: config.database ?? { path: "" },
    workspace: config.workspace ?? { workdir: process.cwd() },
    visionFallback: config.visionFallback ?? {
      enabled: false,
      url: "http://localhost:11434",
      model: "qwen3.5:0.8b",
      timeout: 120
    }
  };
}
function addProvider(config, provider) {
  const newProvider = {
    ...provider,
    id: randomUUID(),
    createdAt: (/* @__PURE__ */ new Date()).toISOString()
  };
  const shouldActivate = provider.isActive || (config.providers?.length ?? 0) === 0;
  return {
    providers: [
      ...(config.providers ?? []).map((p) => shouldActivate ? { ...p, isActive: false } : p),
      { ...newProvider, isActive: shouldActivate }
    ],
    defaultModelSelection: shouldActivate ? `${newProvider.id}/auto` : config.defaultModelSelection,
    activeProviderId: shouldActivate ? newProvider.id : config.activeProviderId,
    activeWorkflowId: config.activeWorkflowId,
    server: config.server ?? { port: 10369, host: "127.0.0.1", openBrowser: true },
    logging: config.logging ?? { level: "error" },
    database: config.database ?? { path: "" },
    workspace: config.workspace ?? { workdir: process.cwd() },
    visionFallback: config.visionFallback ?? {
      enabled: false,
      url: "http://localhost:11434",
      model: "qwen3.5:0.8b",
      timeout: 120
    }
  };
}
function removeProvider(config, providerId) {
  const currentProviders = config.providers ?? [];
  const filtered = currentProviders.filter((p) => p.id !== providerId);
  let newDefaultModelSelection = config.defaultModelSelection;
  if (config.defaultModelSelection) {
    const slashIndex = config.defaultModelSelection.indexOf("/");
    const selectedProviderId = slashIndex === -1 ? config.defaultModelSelection : config.defaultModelSelection.substring(0, slashIndex);
    if (selectedProviderId === providerId) {
      newDefaultModelSelection = filtered.length > 0 ? `${filtered[0].id}/auto` : void 0;
    }
  }
  const wasActive = config.activeProviderId === providerId;
  const newActiveId = wasActive && filtered.length > 0 ? filtered[0].id : wasActive ? void 0 : config.activeProviderId;
  return {
    providers: filtered.map((p) => ({ ...p, isActive: p.id === newActiveId })),
    activeProviderId: newActiveId,
    defaultModelSelection: newDefaultModelSelection,
    activeWorkflowId: config.activeWorkflowId,
    server: config.server ?? { port: 10369, host: "127.0.0.1", openBrowser: true },
    logging: config.logging ?? { level: "error" },
    database: config.database ?? { path: "" },
    workspace: config.workspace ?? { workdir: process.cwd() },
    visionFallback: config.visionFallback ?? {
      enabled: false,
      url: "http://localhost:11434",
      model: "qwen3.5:0.8b",
      timeout: 120
    }
  };
}
function activateProvider(config, providerId) {
  const provider = config.providers?.find((p) => p.id === providerId);
  if (!provider) {
    return {
      providers: config.providers ?? [],
      defaultModelSelection: config.defaultModelSelection,
      activeProviderId: config.activeProviderId,
      activeWorkflowId: config.activeWorkflowId,
      server: config.server ?? { port: 10369, host: "127.0.0.1", openBrowser: true },
      logging: config.logging ?? { level: "error" },
      database: config.database ?? { path: "" },
      workspace: config.workspace ?? { workdir: process.cwd() },
      visionFallback: config.visionFallback ?? {
        enabled: false,
        url: "http://localhost:11434",
        model: "qwen3.5:0.8b",
        timeout: 120
      }
    };
  }
  return {
    providers: (config.providers ?? []).map((p) => ({ ...p, isActive: p.id === providerId })),
    defaultModelSelection: config.defaultModelSelection,
    activeProviderId: providerId,
    activeWorkflowId: config.activeWorkflowId,
    server: config.server ?? { port: 10369, host: "127.0.0.1", openBrowser: true },
    logging: config.logging ?? { level: "error" },
    database: config.database ?? { path: "" },
    workspace: config.workspace ?? { workdir: process.cwd() },
    visionFallback: config.visionFallback ?? {
      enabled: false,
      url: "http://localhost:11434",
      model: "qwen3.5:0.8b",
      timeout: 120
    }
  };
}
function mergeConfigs(...configs) {
  const result = configs.reduce(
    (acc, curr) => {
      if (curr.llm) {
        acc.llm = { ...acc.llm, ...curr.llm };
      }
      if (curr.server) {
        acc.server = { ...acc.server, ...curr.server };
      }
      if (curr.logging) {
        acc.logging = { ...acc.logging, ...curr.logging };
      }
      return acc;
    },
    {
      llm: {
        url: "http://localhost:8000/v1",
        model: "auto",
        backend: "auto",
        maxContext: 2e5,
        disableThinking: false
      },
      server: { port: 10369, host: "127.0.0.1", openBrowser: true },
      logging: { level: "error" }
    }
  );
  return oldConfigSchema.parse(result);
}

export {
  trySmartDefaults,
  configFileExists,
  getVisionFallback,
  migrateConfig,
  loadGlobalConfig,
  getDefaultVisionFallback,
  saveGlobalConfig,
  getActiveProvider,
  getDefaultModel,
  setDefaultModelSelection,
  addProvider,
  removeProvider,
  activateProvider,
  mergeConfigs
};
//# sourceMappingURL=chunk-NNEHZT3V.js.map