#!/usr/bin/env node

// src/bin/package/fix.ts
import chalk2 from "chalk";

// src/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/lib/match.ts
import { minimatch } from "minimatch";
function makeMatcher(pattern, options = {}) {
  const patterns = Array.isArray(pattern) ? pattern : [pattern];
  return (input) => patterns.some((p) => minimatch(input, p, options));
}

// src/actions/package/lint.ts
import { readdirSync } from "node:fs";
import path from "node:path";
import { cwd } from "node:process";
import { pathToFileURL } from "node:url";
import chalk from "chalk";
import { ESLint } from "eslint";
import { findUp } from "find-up";
var dumpMessages = (lintResults) => {
  const colors = ["white", "yellow", "red"];
  const severity = ["none", "warning", "error"];
  for (const lintResult of lintResults) {
    if (lintResult.messages.length > 0) {
      console.log(chalk.gray(`
${lintResult.filePath}`));
      for (const message of lintResult.messages) {
        console.log(
          chalk.gray(`	${message.line}:${message.column}`),
          chalk[colors[message.severity]](`	${severity[message.severity]}`),
          chalk.white(`	${message.message}`),
          chalk.gray(`	${message.ruleId}`)
        );
      }
    }
  }
};
async function getRootESLintConfig() {
  const configPath = await findUp(["eslint.config.ts", "eslint.config.mjs"]);
  if (configPath === void 0) {
    throw new Error("eslint.config.ts not found in the monorepo");
  }
  return pathToFileURL(configPath);
}
function getFiles(dir, ignoreFolders) {
  const currentDirectory = cwd();
  const subdirectory = dir.split(currentDirectory)[1]?.split("/", 2)[1];
  if (ignoreFolders.includes(subdirectory)) return [];
  return readdirSync(dir, { withFileTypes: true }).flatMap((dirent) => {
    const res = path.resolve(dir, dirent.name);
    const relativePath = subdirectory === void 0 ? dirent.name : `${subdirectory}/${dirent.name}`;
    if (makeMatcher(ignoreFolders)(relativePath)) return [];
    return dirent.isDirectory() ? getFiles(res, ignoreFolders) : [res];
  });
}
var packageLint = async (shouldFix = false, isVerbose = false, shouldUseCache = true) => {
  const pkg = INIT_CWD();
  const configPath = await getRootESLintConfig();
  const { default: eslintConfig } = await import(configPath.href);
  const start = Date.now();
  const ignoreFolders = ["node_modules", "dist", "packages", ".git", "build", ".yarn", ".vscode", ".github"];
  const engine = new ESLint({
    baseConfig: [...eslintConfig],
    cache: shouldUseCache,
    fix: shouldFix,
    warnIgnored: false
  });
  const files = getFiles(cwd(), ignoreFolders);
  console.log(chalk.green(`Linting ${pkg} [files = ${files.length}]`));
  if (isVerbose) {
    for (const file of files) {
      console.log(chalk.gray(`	${file}`));
    }
  }
  const lintResults = await engine.lintFiles(files);
  dumpMessages(lintResults);
  if (shouldFix) {
    await ESLint.outputFixes(lintResults);
  }
  const filesCountColor = files.length < 100 ? "green" : files.length < 1e3 ? "yellow" : "red";
  const lintTime = Date.now() - start;
  const lintTimeColor = lintTime < 1e3 ? "green" : lintTime < 3e3 ? "yellow" : "red";
  console.log(chalk.white(`Linted ${chalk[filesCountColor](files.length)} files in ${chalk[lintTimeColor](lintTime)}ms`));
  return lintResults.reduce((prev, lintResult) => prev + lintResult.errorCount, 0);
};

// src/bin/package/fix.ts
try {
  const value = await packageLint(true);
  if (value) {
    process.exit(value);
  }
} catch (reason) {
  console.error(chalk2.red(reason));
  process.exit(-1);
}
//# sourceMappingURL=fix.mjs.map
