import { readFileSync, readdirSync } from 'node:fs';
import { resolve, relative, join } from 'node:path';
import { fileURLToPath } from 'node:url';

// src/exports/declaration-alias-check.ts
var FORBIDDEN_DECLARATION_ALIAS_PATTERNS = [/@platform\//, /@features\//];
function collectDeclarationFiles(directoryPath) {
  const entries = readdirSync(directoryPath, { withFileTypes: true });
  return entries.flatMap((entry) => {
    const entryPath = join(directoryPath, entry.name);
    if (entry.isDirectory()) {
      return collectDeclarationFiles(entryPath);
    }
    return entry.name.endsWith(".d.ts") ? [entryPath] : [];
  });
}
function countDeclarationFiles(declarationRootDir) {
  return collectDeclarationFiles(resolve(declarationRootDir)).length;
}
function findForbiddenDeclarationAliases(declarationRootDir) {
  const absoluteRootDir = resolve(declarationRootDir);
  const declarationFiles = collectDeclarationFiles(absoluteRootDir);
  return declarationFiles.flatMap((filePath) => {
    const content = readFileSync(filePath, "utf8");
    const matchedPatterns = FORBIDDEN_DECLARATION_ALIAS_PATTERNS.filter((pattern) => pattern.test(content)).map((pattern) => pattern.source);
    if (matchedPatterns.length === 0) {
      return [];
    }
    return [
      {
        filePath: relative(absoluteRootDir, filePath),
        matchedPatterns
      }
    ];
  });
}
function formatForbiddenDeclarationAliasError(offenders) {
  return [
    "declaration \uC0B0\uCD9C\uBB3C\uC5D0 \uB0B4\uBD80 alias\uAC00 \uB0A8\uC544 downstream \uD0C0\uC785 \uD574\uC11D\uC774 \uAE68\uC9C8 \uC218 \uC788\uC2B5\uB2C8\uB2E4.",
    "\uC544\uB798 \uD30C\uC77C\uC5D0\uC11C @platform/* \uB610\uB294 @features/* alias\uB97C \uC81C\uAC70\uD558\uAC70\uB098, declaration rewrite \uC804\uB7B5\uC744 \uCD94\uAC00\uD574\uC57C \uD569\uB2C8\uB2E4.",
    JSON.stringify(offenders, null, 2)
  ].join("\n");
}
function assertDeclarationAliasSafety(declarationRootDir) {
  if (countDeclarationFiles(declarationRootDir) === 0) {
    throw new Error(`declaration \uD30C\uC77C\uC774 \uC0DD\uC131\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4: ${resolve(declarationRootDir)}`);
  }
  const offenders = findForbiddenDeclarationAliases(declarationRootDir);
  if (offenders.length > 0) {
    throw new Error(formatForbiddenDeclarationAliasError(offenders));
  }
}
function runDeclarationAliasCheckCli() {
  const declarationRootDir = process.argv[2] || "dist";
  assertDeclarationAliasSafety(declarationRootDir);
  console.log(`declaration alias check passed: ${resolve(declarationRootDir)}`);
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  runDeclarationAliasCheckCli();
}

export { FORBIDDEN_DECLARATION_ALIAS_PATTERNS, assertDeclarationAliasSafety, countDeclarationFiles, findForbiddenDeclarationAliases, formatForbiddenDeclarationAliasError };
