import {
  getActiveProvider,
  getDefaultModel,
  loadGlobalConfig
} from "./chunk-NNEHZT3V.js";
import {
  VERSION,
  createServer
} from "./chunk-ZPCJLFAG.js";
import "./chunk-PDPXHSNZ.js";
import "./chunk-RYEZ7LDX.js";
import "./chunk-PSJIT5LZ.js";
import "./chunk-XAMAYRDA.js";
import "./chunk-DL6ZILAF.js";
import "./chunk-PBGOZMVY.js";
import "./chunk-VRGRAQDG.js";
import "./chunk-RF2JGDSS.js";
import "./chunk-HHAJ3QF6.js";
import "./chunk-HGAMIPFO.js";
import "./chunk-J335KZ6U.js";
import "./chunk-FBGWG4N6.js";
import "./chunk-6WZI6F6G.js";
import "./chunk-RCQOHFAN.js";
import "./chunk-BJYPTN5S.js";
import "./chunk-VUQCQXXJ.js";
import "./chunk-MEYDERUX.js";
import {
  ensureDataDirExists,
  getDatabasePath,
  getGlobalConfigPath
} from "./chunk-CQGTEGKL.js";
import {
  loadConfig
} from "./chunk-CGZHLM3K.js";
import "./chunk-SZKEGZIB.js";
import {
  logger
} from "./chunk-K44MW7JJ.js";

// src/server/utils/network.ts
import os from "os";
import { statSync } from "fs";
function getNetworkInterfaces() {
  const interfaces = os.networkInterfaces();
  const result = [];
  for (const [name, addresses] of Object.entries(interfaces)) {
    if (!addresses) continue;
    for (const addr of addresses) {
      if (addr.family === "IPv4") {
        result.push({
          ip: addr.address,
          family: "IPv4",
          name
        });
      }
    }
  }
  return result;
}
function getValidIPv4Addresses() {
  const interfaces = getNetworkInterfaces();
  const valid = interfaces.filter((addr) => {
    if (addr.ip.startsWith("127.")) return false;
    if (addr.ip.startsWith("169.254.")) return false;
    return true;
  }).map((addr) => addr.ip);
  const sorted = valid.sort((a, b) => {
    const aInterface = interfaces.find((i) => i.ip === a)?.name || "";
    const bInterface = interfaces.find((i) => i.ip === b)?.name || "";
    if (aInterface.startsWith("eth") && !bInterface.startsWith("eth")) return -1;
    if (!aInterface.startsWith("eth") && bInterface.startsWith("eth")) return 1;
    if (aInterface.startsWith("wlan") && !bInterface.startsWith("wlan")) return -1;
    if (!aInterface.startsWith("wlan") && bInterface.startsWith("wlan")) return 1;
    return 0;
  });
  return sorted;
}
function formatFileSize(bytes) {
  if (bytes === 0) return "0KB";
  const KB = 1024;
  const MB = KB * 1024;
  const GB = MB * 1024;
  if (bytes >= GB) {
    return `${(bytes / GB).toFixed(1)}GB`;
  } else if (bytes >= MB) {
    return `${(bytes / MB).toFixed(1)}MB`;
  } else {
    return `${Math.round(bytes / KB)}KB`;
  }
}
function getDatabaseSize(databasePath) {
  try {
    const stats = statSync(databasePath);
    return formatFileSize(stats.size);
  } catch {
    return "0KB";
  }
}
function displayStartupBanner(config) {
  const { host, port, databasePath, configPath } = config;
  const isLocalhost = host === "127.0.0.1";
  console.log(`
\u{1F98A} OpenFox v${VERSION}
`);
  if (isLocalhost) {
    console.log(`  \u{1F310} Server: http://localhost:${port}`);
    console.log("  \u{1F512} Access: Localhost only");
  } else {
    const ips = getValidIPv4Addresses();
    if (ips.length === 0) {
      console.log(`  \u{1F310} Server: http://0.0.0.0:${port}`);
      console.warn("  \u26A0\uFE0F  Warning: No valid network interfaces detected");
    } else {
      console.log("  \u{1F310} Server:");
      for (const ip of ips) {
        console.log(`     \u2022 http://${ip}:${port}`);
      }
      console.log("  \u{1F30D} Access: Local network");
    }
  }
  const size = getDatabaseSize(databasePath);
  console.log(`  \u{1F4BE} Database: ${databasePath} (${size})`);
  console.log(`  \u2699\uFE0F  Config:  ${configPath}`);
  console.log("\n\u{1F4A1} Tip: Press Ctrl+C to stop the server\n");
}

// src/cli/serve.ts
import open from "open";
async function runServe(options) {
  const { mode, port, openBrowser } = options;
  await ensureDataDirExists(mode);
  const globalConfig = await loadGlobalConfig(mode);
  const activeProvider = getActiveProvider(globalConfig);
  const env = loadConfig();
  const envBackend = env.llm.backend;
  const envModel = env.llm.model;
  const envUrl = env.llm.baseUrl;
  const isEnvBackendExplicit = envBackend !== "auto";
  const isEnvModelExplicit = envModel !== "qwen3.5-122b-int4-autoround";
  const isEnvUrlExplicit = envUrl !== "http://localhost:8000/v1";
  const providerUrl = activeProvider?.url ?? envUrl;
  const defaultModel = getDefaultModel(globalConfig) ?? envModel;
  const providerBackend = activeProvider?.backend ?? envBackend;
  const merged = {
    ...env,
    llm: {
      ...env.llm,
      baseUrl: isEnvUrlExplicit ? envUrl : providerUrl,
      model: isEnvModelExplicit ? envModel : defaultModel,
      backend: isEnvBackendExplicit ? envBackend : providerBackend
    },
    server: {
      ...env.server,
      port: port ?? env.server.port,
      host: env.server.host ?? globalConfig.server.host ?? "127.0.0.1",
      openBrowser: openBrowser ?? globalConfig.server.openBrowser
    },
    database: {
      // Use env OPENFOX_DB_PATH if explicitly set (e.g., ":memory:" for tests), otherwise use standard path
      path: env.database.path !== "./openfox.db" ? env.database.path : getDatabasePath(mode)
    },
    logging: {
      level: globalConfig.logging?.level ?? "error"
    },
    mode,
    // Pass providers for the server to use
    providers: globalConfig.providers,
    activeProviderId: globalConfig.activeProviderId,
    activeWorkflowId: globalConfig.activeWorkflowId,
    defaultModelSelection: globalConfig.defaultModelSelection,
    // Workdir precedence: .env override → global config → process.cwd()
    // Normalize: remove trailing slash to prevent double slashes in paths
    workdir: (process.env["OPENFOX_WORKDIR"] ?? globalConfig.workspace?.workdir ?? process.cwd()).replace(/\/$/, "")
  };
  await createServer(merged);
  displayStartupBanner({
    host: merged.server.host,
    port: merged.server.port,
    databasePath: merged.database.path,
    configPath: getGlobalConfigPath(mode)
  });
  if (merged.server.openBrowser) {
    open(`http://${merged.server.host === "127.0.0.1" ? "localhost" : merged.server.host}:${merged.server.port}`).catch(
      () => {
        logger.warn("Could not open browser automatically");
      }
    );
  }
}
export {
  runServe
};
//# sourceMappingURL=serve-SGFEQ5N7.js.map