import fs from "node:fs";
import { createRequire } from "node:module";
import { performance } from "node:perf_hooks";
import colors from "piccolore";
import { gt, major, minor, patch } from "semver";
import { getDataStoreFile } from "../../content/content-layer.js";
import { globalContentLayer } from "../../content/instance.js";
import { attachContentServerListeners } from "../../content/index.js";
import { MutableDataStore } from "../../content/mutable-data-store.js";
import { globalContentConfigObserver } from "../../content/utils.js";
import { telemetry } from "../../events/index.js";
import * as msg from "../messages/runtime.js";
import { newVersionAvailable } from "../messages/node.js";
import { ensureProcessNodeEnv } from "../util.js";
import { startContainer } from "./container.js";
import { createContainerWithAutomaticRestart } from "./restart.js";
import {
  fetchLatestAstroVersion,
  MAX_PATCH_DISTANCE,
  shouldCheckForUpdates
} from "./update-check.js";
import { BuildTimeAstroVersionProvider } from "../../cli/infra/build-time-astro-version-provider.js";
import { piccoloreTextStyler } from "../../cli/infra/piccolore-text-styler.js";
function warnIfVite8({ root, logger }) {
  try {
    const require2 = createRequire(root);
    const { version } = require2("vite/package.json");
    if (major(version) >= 8) {
      logger.warn("SKIP_FORMAT", msg.vite8Warning({ viteVersion: version }));
    }
  } catch {
  }
}
async function dev(inlineConfig) {
  ensureProcessNodeEnv("development");
  const devStart = performance.now();
  await telemetry.record([]);
  const restart = await createContainerWithAutomaticRestart({ inlineConfig, fs });
  const logger = restart.container.logger;
  const currentVersion = "6.3.1";
  const isPrerelease = currentVersion.includes("-");
  if (!isPrerelease) {
    try {
      shouldCheckForUpdates(restart.container.settings.preferences).then(async (shouldCheck) => {
        if (shouldCheck) {
          const version = await fetchLatestAstroVersion(restart.container.settings.preferences);
          if (gt(version, currentVersion)) {
            restart.container.settings.latestAstroVersion = version;
            const sameMajor = major(version) === major(currentVersion);
            const sameMinor = minor(version) === minor(currentVersion);
            const patchDistance = patch(version) - patch(currentVersion);
            if (sameMajor && sameMinor && patchDistance < MAX_PATCH_DISTANCE) {
              return;
            }
            logger.warn(
              "SKIP_FORMAT",
              await newVersionAvailable({
                latestVersion: version
              })
            );
          }
        }
      }).catch(() => {
      });
    } catch {
    }
  }
  let store;
  try {
    const dataStoreFile = getDataStoreFile(restart.container.settings, true);
    store = await MutableDataStore.fromFile(dataStoreFile);
  } catch (err) {
    logger.error("content", err.message);
  }
  if (!store) {
    logger.error("content", "Failed to create data store");
  }
  await attachContentServerListeners(restart.container);
  const config = globalContentConfigObserver.get();
  if (config.status === "error") {
    logger.error("content", config.error.message);
  }
  if (config.status === "loaded" && store) {
    const contentLayer = globalContentLayer.init({
      settings: restart.container.settings,
      logger,
      watcher: restart.container.viteServer.watcher,
      store
    });
    contentLayer.watchContentConfig();
    await contentLayer.sync();
  } else if (config.status !== "does-not-exist") {
    logger.warn("content", "Content config not loaded");
  }
  const devServerAddressInfo = await startContainer(restart.container);
  restart.bindCLIShortcuts();
  logger.info(
    "SKIP_FORMAT",
    msg.serverStart({
      startupTime: performance.now() - devStart,
      resolvedUrls: restart.container.viteServer.resolvedUrls || { local: [], network: [] },
      host: restart.container.settings.config.server.host,
      base: restart.container.settings.config.base,
      astroVersionProvider: new BuildTimeAstroVersionProvider(),
      textStyler: piccoloreTextStyler
    })
  );
  if (isPrerelease) {
    logger.warn("SKIP_FORMAT", msg.prerelease({ currentVersion }));
  }
  if (restart.container.viteServer.config.server?.fs?.strict === false) {
    logger.warn("SKIP_FORMAT", msg.fsStrictWarning());
  }
  setImmediate(() => warnIfVite8({ root: restart.container.settings.config.root, logger }));
  logger.info(null, colors.green("watching for file changes..."));
  return {
    address: devServerAddressInfo,
    get watcher() {
      return restart.container.viteServer.watcher;
    },
    handle(req, res) {
      return restart.container.handle(req, res);
    },
    async stop() {
      await restart.container.close();
    }
  };
}
export {
  dev as default
};
