'use strict';

var fs2 = require('fs');
var path = require('path');
var module$1 = require('module');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var fs2__default = /*#__PURE__*/_interopDefault(fs2);
var path__default = /*#__PURE__*/_interopDefault(path);

// src/features/gen-html/infrastructure/local-server/dependencies/style-bridges.ts
var LOCAL_SERVER_STYLE_EXPORT_FILE_PATTERN = /\.(?:css|s[ac]ss)$/i;
new Set(
  module$1.builtinModules.flatMap((moduleName) => [moduleName, moduleName.replace(/^node:/, ""), `node:${moduleName.replace(/^node:/, "")}`])
);
function getLocalServerPaths(paths) {
  const directoryPath = path__default.default.join(paths.baseDir, "local-server");
  const generatedDirectoryPath = path__default.default.join(directoryPath, "generated");
  const multipleDirectoryPath = path__default.default.join(directoryPath, "multiple");
  const storybookConfigDirectoryPath = path__default.default.join(directoryPath, ".storybook");
  return {
    directoryPath,
    generatedDirectoryPath,
    generatedRegistryPath: path__default.default.join(directoryPath, "generated-registry.json"),
    multipleDirectoryPath,
    logPath: path__default.default.join(directoryPath, "server.log"),
    packageJsonPath: path__default.default.join(directoryPath, "package.json"),
    packageCustomJsonPath: path__default.default.join(directoryPath, "package-custom.json"),
    previewTargetPath: path__default.default.join(directoryPath, "preview-target.json"),
    refreshLockPath: path__default.default.join(directoryPath, "refresh.lock"),
    scssModuleDeclarationPath: path__default.default.join(directoryPath, "scss.d.ts"),
    serverLockPath: path__default.default.join(directoryPath, "server.lock"),
    statePath: path__default.default.join(directoryPath, "server-state.json"),
    storybookConfigDirectoryPath,
    storybookMainConfigPath: path__default.default.join(storybookConfigDirectoryPath, "main.ts"),
    storybookManagerConfigPath: path__default.default.join(storybookConfigDirectoryPath, "manager.tsx"),
    storybookPreviewConfigPath: path__default.default.join(storybookConfigDirectoryPath, "preview.ts"),
    tsconfigPath: path__default.default.join(directoryPath, "tsconfig.json")
  };
}
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function readJsonFile(filePath) {
  if (!fs2__default.default.existsSync(filePath)) {
    return void 0;
  }
  const raw = fs2__default.default.readFileSync(filePath, "utf8").trim();
  if (!raw) {
    return void 0;
  }
  return JSON.parse(raw);
}

// src/features/gen-html/infrastructure/local-server/dependencies/manifest.ts
function normalizeDependencies(value) {
  if (!isRecord(value)) {
    return {};
  }
  return Object.entries(value).reduce((accumulator, [key, dependencyValue]) => {
    if (typeof dependencyValue === "string" && dependencyValue.trim()) {
      accumulator[key] = dependencyValue;
    }
    return accumulator;
  }, {});
}

// src/features/gen-html/infrastructure/local-server/dependencies/style-bridges.ts
function resolveLocalServerStyleExportTarget(value) {
  if (typeof value === "string") {
    return LOCAL_SERVER_STYLE_EXPORT_FILE_PATTERN.test(value) ? value : "";
  }
  if (Array.isArray(value)) {
    for (const entry of value) {
      const resolvedTarget = resolveLocalServerStyleExportTarget(entry);
      if (resolvedTarget) {
        return resolvedTarget;
      }
    }
    return "";
  }
  if (isRecord(value)) {
    return resolveLocalServerStyleExportTarget(value.default) || resolveLocalServerStyleExportTarget(value.import) || resolveLocalServerStyleExportTarget(value.require);
  }
  return "";
}
function buildLocalServerStyleExportBridgeContent(bridgeFilePath, targetFilePath) {
  const relativeTargetPath = path__default.default.relative(path__default.default.dirname(bridgeFilePath), targetFilePath).split(path__default.default.sep).join("/");
  const normalizedTargetPath = relativeTargetPath.startsWith(".") ? relativeTargetPath : `./${relativeTargetPath}`;
  if (path__default.default.extname(targetFilePath).toLowerCase() === ".css") {
    return `@import '${normalizedTargetPath}';
`;
  }
  return `@forward '${normalizedTargetPath}';
`;
}
function synchronizeLocalServerStyleExportBridges(paths, trace) {
  const { directoryPath, packageJsonPath } = getLocalServerPaths(paths);
  const localServerPackageJson = readJsonFile(packageJsonPath);
  const dependencyNames = Object.keys(normalizeDependencies(localServerPackageJson?.dependencies));
  for (const dependencyName of dependencyNames) {
    const dependencyDirectoryPath = path__default.default.join(directoryPath, "node_modules", ...dependencyName.split("/"));
    const dependencyPackageJsonPath = path__default.default.join(dependencyDirectoryPath, "package.json");
    const dependencyPackageJson = readJsonFile(dependencyPackageJsonPath);
    const dependencyExports = isRecord(dependencyPackageJson?.exports) ? dependencyPackageJson.exports : {};
    for (const [exportKey, exportValue] of Object.entries(dependencyExports)) {
      if (!exportKey.startsWith("./")) {
        continue;
      }
      const exportTargetPath = resolveLocalServerStyleExportTarget(exportValue);
      if (!exportTargetPath) {
        continue;
      }
      const exportSubpath = exportKey.slice(2);
      if (!exportSubpath) {
        continue;
      }
      const targetFilePath = path__default.default.resolve(dependencyDirectoryPath, exportTargetPath);
      if (!fs2__default.default.existsSync(targetFilePath) || !fs2__default.default.statSync(targetFilePath).isFile()) {
        trace("local-server:style-export-bridge:missing-target", `${dependencyName} ${exportKey} -> ${targetFilePath}`);
        continue;
      }
      const bridgeFilePath = path__default.default.join(
        dependencyDirectoryPath,
        ...exportSubpath.split("/").filter(Boolean)
      ) + path__default.default.extname(targetFilePath);
      const bridgeContent = buildLocalServerStyleExportBridgeContent(bridgeFilePath, targetFilePath);
      const currentBridgeContent = fs2__default.default.existsSync(bridgeFilePath) ? fs2__default.default.readFileSync(bridgeFilePath, "utf8") : "";
      if (currentBridgeContent === bridgeContent) {
        continue;
      }
      fs2__default.default.mkdirSync(path__default.default.dirname(bridgeFilePath), { recursive: true });
      fs2__default.default.writeFileSync(bridgeFilePath, bridgeContent, "utf8");
      trace("local-server:style-export-bridge:written", `${dependencyName} ${exportKey} -> ${bridgeFilePath}`);
    }
  }
}

exports.synchronizeLocalServerStyleExportBridges = synchronizeLocalServerStyleExportBridges;
