import fs2 from 'node:fs';
import path from 'node:path';
import { builtinModules } from 'node:module';

// 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(
  builtinModules.flatMap((moduleName) => [moduleName, moduleName.replace(/^node:/, ""), `node:${moduleName.replace(/^node:/, "")}`])
);
function getLocalServerPaths(paths) {
  const directoryPath = path.join(paths.baseDir, "local-server");
  const generatedDirectoryPath = path.join(directoryPath, "generated");
  const multipleDirectoryPath = path.join(directoryPath, "multiple");
  const storybookConfigDirectoryPath = path.join(directoryPath, ".storybook");
  return {
    directoryPath,
    generatedDirectoryPath,
    generatedRegistryPath: path.join(directoryPath, "generated-registry.json"),
    multipleDirectoryPath,
    logPath: path.join(directoryPath, "server.log"),
    packageJsonPath: path.join(directoryPath, "package.json"),
    packageCustomJsonPath: path.join(directoryPath, "package-custom.json"),
    previewTargetPath: path.join(directoryPath, "preview-target.json"),
    refreshLockPath: path.join(directoryPath, "refresh.lock"),
    scssModuleDeclarationPath: path.join(directoryPath, "scss.d.ts"),
    serverLockPath: path.join(directoryPath, "server.lock"),
    statePath: path.join(directoryPath, "server-state.json"),
    storybookConfigDirectoryPath,
    storybookMainConfigPath: path.join(storybookConfigDirectoryPath, "main.ts"),
    storybookManagerConfigPath: path.join(storybookConfigDirectoryPath, "manager.tsx"),
    storybookPreviewConfigPath: path.join(storybookConfigDirectoryPath, "preview.ts"),
    tsconfigPath: path.join(directoryPath, "tsconfig.json")
  };
}
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function readJsonFile(filePath) {
  if (!fs2.existsSync(filePath)) {
    return void 0;
  }
  const raw = fs2.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.relative(path.dirname(bridgeFilePath), targetFilePath).split(path.sep).join("/");
  const normalizedTargetPath = relativeTargetPath.startsWith(".") ? relativeTargetPath : `./${relativeTargetPath}`;
  if (path.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.join(directoryPath, "node_modules", ...dependencyName.split("/"));
    const dependencyPackageJsonPath = path.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.resolve(dependencyDirectoryPath, exportTargetPath);
      if (!fs2.existsSync(targetFilePath) || !fs2.statSync(targetFilePath).isFile()) {
        trace("local-server:style-export-bridge:missing-target", `${dependencyName} ${exportKey} -> ${targetFilePath}`);
        continue;
      }
      const bridgeFilePath = path.join(
        dependencyDirectoryPath,
        ...exportSubpath.split("/").filter(Boolean)
      ) + path.extname(targetFilePath);
      const bridgeContent = buildLocalServerStyleExportBridgeContent(bridgeFilePath, targetFilePath);
      const currentBridgeContent = fs2.existsSync(bridgeFilePath) ? fs2.readFileSync(bridgeFilePath, "utf8") : "";
      if (currentBridgeContent === bridgeContent) {
        continue;
      }
      fs2.mkdirSync(path.dirname(bridgeFilePath), { recursive: true });
      fs2.writeFileSync(bridgeFilePath, bridgeContent, "utf8");
      trace("local-server:style-export-bridge:written", `${dependencyName} ${exportKey} -> ${bridgeFilePath}`);
    }
  }
}

export { synchronizeLocalServerStyleExportBridges };
