import {
  ErrorCodes,
  createError
} from "./chunk-RXRKBBSM.js";

// src/template-directory-resolver.ts
import * as fs from "fs";
import * as path from "path";
import { fileURLToPath } from "url";
var CLI_SCOPE_DIR = "@lumenflow";
var CLI_PACKAGE_DIR = "cli";
var TEMPLATES_DIR = "templates";
var PACKAGES_DIR = "packages";
function collectAncestorDirectories(startDir) {
  const directories = [];
  let current = path.resolve(startDir);
  while (true) {
    directories.push(current);
    const parent = path.dirname(current);
    if (parent === current) {
      return directories;
    }
    current = parent;
  }
}
function isCliPackageRoot(candidate) {
  return path.basename(candidate) === CLI_PACKAGE_DIR && path.basename(path.dirname(candidate)) === CLI_SCOPE_DIR;
}
function collectCwdCandidates(cwd) {
  const candidates = [];
  for (const directory of collectAncestorDirectories(cwd)) {
    if (isCliPackageRoot(directory)) {
      candidates.push(path.join(directory, TEMPLATES_DIR));
    }
    candidates.push(
      path.join(directory, PACKAGES_DIR, CLI_SCOPE_DIR, CLI_PACKAGE_DIR, TEMPLATES_DIR)
    );
  }
  return candidates;
}
function collectModuleCandidates(moduleUrl) {
  const modulePath = fileURLToPath(moduleUrl);
  const moduleDir = path.dirname(modulePath);
  const packageRoot = path.resolve(moduleDir, "..");
  return [path.join(packageRoot, TEMPLATES_DIR)];
}
function dedupeCandidates(candidates) {
  const seen = /* @__PURE__ */ new Set();
  const unique = [];
  for (const candidate of candidates) {
    const normalized = path.resolve(candidate);
    if (seen.has(normalized)) {
      continue;
    }
    seen.add(normalized);
    unique.push(normalized);
  }
  return unique;
}
function resolveCliTemplatesDir(options = {}) {
  const existsSync2 = options.existsSync ?? fs.existsSync;
  const cwd = options.cwd ?? process.cwd();
  const moduleUrl = options.moduleUrl ?? import.meta.url;
  const candidates = dedupeCandidates([
    ...collectCwdCandidates(cwd),
    ...collectModuleCandidates(moduleUrl)
  ]);
  for (const candidate of candidates) {
    if (existsSync2(candidate)) {
      return candidate;
    }
  }
  throw createError(
    ErrorCodes.FILE_NOT_FOUND,
    `Templates directory not found. Checked: ${candidates.join(", ")}`
  );
}

export {
  resolveCliTemplatesDir
};
