// src/actions/skills/detectProfile.ts
import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
import PATH4 from "node:path";

// src/lib/updo/collectWorkspaceDeps.ts
import { readFileSync } from "node:fs";
import PATH from "node:path";
var DEP_FIELDS = ["dependencies", "devDependencies", "peerDependencies"];
function collectExternalWorkspaceDeps(deps, depField, ws, workspaceNames, declaredDeps) {
  if (!deps) return;
  for (const [name, range] of Object.entries(deps)) {
    if (workspaceNames.has(name)) continue;
    if (range.startsWith("workspace:")) continue;
    declaredDeps.push({
      depType: depField,
      name,
      range,
      workspaceLocation: ws.location,
      workspaceName: ws.name
    });
  }
}
function collectWorkspaceDeps(cwd, workspaces, workspaceNames) {
  const declaredDeps = [];
  for (const ws of workspaces) {
    const pkgPath = PATH.resolve(cwd, ws.location, "package.json");
    let pkg;
    try {
      pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
    } catch {
      continue;
    }
    for (const depField of DEP_FIELDS) {
      collectExternalWorkspaceDeps(
        pkg[depField],
        depField,
        ws,
        workspaceNames,
        declaredDeps
      );
    }
  }
  return declaredDeps;
}

// src/lib/updo/runUpdo.ts
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
import PATH3 from "node:path";
import chalk from "chalk";

// src/pm/workspaces.ts
import { existsSync, readFileSync as readFileSync2 } from "node:fs";
import PATH2 from "node:path";
import { globSync } from "glob";
function readJsonFile(path) {
  if (!existsSync(path)) return void 0;
  try {
    return JSON.parse(readFileSync2(path, "utf8"));
  } catch {
    return void 0;
  }
}
function readRootPackageJson(cwd = process.cwd()) {
  return readJsonFile(PATH2.resolve(cwd, "package.json"));
}
function readWorkspacePatternsFromPackageJson(cwd = process.cwd()) {
  const pkg = readRootPackageJson(cwd);
  if (!pkg?.workspaces) return [];
  if (Array.isArray(pkg.workspaces)) return [...pkg.workspaces];
  return pkg.workspaces.packages ? [...pkg.workspaces.packages] : [];
}
function readPnpmWorkspacePatterns(cwd = process.cwd()) {
  const wsPath = PATH2.resolve(cwd, "pnpm-workspace.yaml");
  if (!existsSync(wsPath)) return [];
  const content = readFileSync2(wsPath, "utf8");
  const patterns = [];
  let isInPackages = false;
  for (const line of content.split("\n")) {
    if (/^packages\s*:/.test(line.trim())) {
      isInPackages = true;
      continue;
    }
    if (isInPackages) {
      const match = /^\s+-\s+['"]?([^'"]+)['"]?\s*$/.exec(line);
      if (match) {
        patterns.push(match[1]);
      } else if (line.trim() !== "" && !/^\s/.test(line)) {
        break;
      }
    }
  }
  return patterns;
}
function readWorkspacePatterns(cwd = process.cwd()) {
  const fromPackageJson = readWorkspacePatternsFromPackageJson(cwd);
  return fromPackageJson.length > 0 ? fromPackageJson : readPnpmWorkspacePatterns(cwd);
}
function workspaceFromPackageJsonMatch(match, cwd, seen) {
  const pkg = readJsonFile(match);
  const name = pkg?.name;
  if (name === void 0 || name.length === 0) return void 0;
  const location = PATH2.relative(cwd, PATH2.dirname(match)) || ".";
  if (seen.has(location)) return void 0;
  seen.add(location);
  return { location, name };
}
function listDeclaredWorkspaces(cwd = process.cwd()) {
  const patterns = readWorkspacePatterns(cwd);
  const seen = /* @__PURE__ */ new Set();
  const workspaces = [];
  for (const pattern of patterns) {
    const matches = globSync(PATH2.posix.join(pattern.replaceAll(PATH2.sep, "/"), "package.json"), {
      absolute: true,
      cwd,
      ignore: ["**/node_modules/**", "**/dist/**", "**/build/**"]
    });
    for (const match of matches) {
      const workspace = workspaceFromPackageJsonMatch(match, cwd, seen);
      if (workspace) workspaces.push(workspace);
    }
  }
  return workspaces.toSorted((a, b) => a.location.localeCompare(b.location));
}

// src/lib/updo/runUpdo.ts
function listWorkspacesFromFs(cwd) {
  const workspaces = listDeclaredWorkspaces(cwd);
  const rootPath = PATH3.resolve(cwd, "package.json");
  if (existsSync2(rootPath)) {
    try {
      const root = JSON.parse(readFileSync3(rootPath, "utf8"));
      if (root.name != null && root.name.length > 0 && workspaces.every((ws) => ws.location !== ".")) {
        workspaces.unshift({ location: ".", name: root.name });
      }
    } catch {
    }
  }
  return workspaces;
}

// src/actions/skills/detectProfile.ts
var XYLABS_SCOPE = "@xylabs/";
var ARIESTOOLS_SCOPE = "@ariestools/";
var XYO_NETWORK_SCOPE = "@xyo-network/";
var XL1_PACKAGE_PREFIX = "@xyo-network/xl1";
var LEGACY_TOOLCHAIN_PACKAGES = /* @__PURE__ */ new Set([
  "@xylabs/ts-scripts-yarn3",
  "@xylabs/ts-scripts-pnpm",
  "@xylabs/ts-scripts-react-yarn3",
  "@xylabs/ts-scripts-common"
]);
var XY_ECOSYSTEM_SCOPES = [XYLABS_SCOPE, ARIESTOOLS_SCOPE, XYO_NETWORK_SCOPE];
var pushUnique = (list, value) => {
  if (!list.includes(value)) list.push(value);
};
var packageScope = (name) => {
  if (!name.startsWith("@")) return void 0;
  const slash = name.indexOf("/");
  if (slash === -1) return void 0;
  return name.slice(0, slash + 1);
};
var isXyoNetworkPackage = (name) => name.startsWith(XYO_NETWORK_SCOPE);
var isXl1Package = (name) => name.startsWith(XL1_PACKAGE_PREFIX);
var isXyEcosystemPackage = (name) => {
  return name.startsWith(XYLABS_SCOPE) || name.startsWith(ARIESTOOLS_SCOPE) || isXyoNetworkPackage(name);
};
var isTrackedImportScope = (scope) => {
  return XY_ECOSYSTEM_SCOPES.includes(scope);
};
var hasToolchainDependency = (depName) => {
  return depName === "@xylabs/toolchain" || LEGACY_TOOLCHAIN_PACKAGES.has(depName);
};
var isUsingXyScripts = (scripts) => {
  if (!scripts) return false;
  return Object.values(scripts).some((script) => /\bxy\b/.test(script));
};
var hasXyConfig = (cwd, workspaces) => {
  const locations = [".", ...workspaces.map((ws) => ws.location)];
  return locations.some((location) => {
    const configPath = PATH4.resolve(cwd, location, "xy.config.ts");
    return existsSync3(configPath);
  });
};
var resolveTier = (produces, imports, isUsingToolchain) => {
  const allPackages = [...produces, ...imports];
  if (allPackages.some(isXl1Package)) return "xl1";
  if (allPackages.some(isXyoNetworkPackage)) return "xyo";
  const hasXyEcosystem = allPackages.some(isXyEcosystemPackage);
  if (hasXyEcosystem || isUsingToolchain) return "xy";
  return "none";
};
var collectProduces = (cwd, workspaces) => {
  const produces = [];
  const signals = [];
  for (const ws of workspaces) {
    const pkgPath = PATH4.resolve(cwd, ws.location, "package.json");
    if (!existsSync3(pkgPath)) continue;
    try {
      const pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
      if (pkg.name != null && pkg.name.length > 0 && isXyEcosystemPackage(pkg.name)) {
        pushUnique(produces, pkg.name);
        pushUnique(signals, `produces ${pkg.name}`);
      }
    } catch {
    }
  }
  return { produces, signals };
};
var collectImports = (declaredDeps) => {
  const imports = [];
  const signals = [];
  for (const dep of declaredDeps) {
    pushUnique(imports, dep.name);
    const scope = packageScope(dep.name);
    if (scope != null && isTrackedImportScope(scope)) {
      pushUnique(signals, `imports ${dep.name}`);
    }
  }
  return { imports, signals };
};
var detectToolchainUsage = (cwd, workspaces, declaredDeps) => {
  const signals = [];
  let isUsesToolchain = hasXyConfig(cwd, workspaces);
  const rootPkgPath = PATH4.resolve(cwd, "package.json");
  if (existsSync3(rootPkgPath)) {
    try {
      const rootPkg = JSON.parse(readFileSync4(rootPkgPath, "utf8"));
      if (isUsingXyScripts(rootPkg.scripts)) {
        isUsesToolchain = true;
        pushUnique(signals, "root scripts invoke xy");
      }
    } catch {
    }
  }
  for (const dep of declaredDeps) {
    if (hasToolchainDependency(dep.name)) {
      isUsesToolchain = true;
      pushUnique(signals, `imports ${dep.name}`);
    }
  }
  if (isUsesToolchain && hasXyConfig(cwd, workspaces)) {
    pushUnique(signals, "xy.config.ts present");
  }
  return { signals, isUsingToolchain: isUsesToolchain };
};
var detectRepoProfile = (cwd) => {
  const workspaces = listWorkspacesFromFs(cwd);
  const workspaceNames = new Set(workspaces.map((ws) => ws.name));
  const declaredDeps = collectWorkspaceDeps(cwd, workspaces, workspaceNames);
  const produced = collectProduces(cwd, workspaces);
  const imported = collectImports(declaredDeps);
  const toolchain = detectToolchainUsage(cwd, workspaces, declaredDeps);
  const signals = [...produced.signals, ...imported.signals, ...toolchain.signals].toSorted((a, b) => a.localeCompare(b));
  return {
    imports: imported.imports.toSorted((a, b) => a.localeCompare(b)),
    produces: produced.produces.toSorted((a, b) => a.localeCompare(b)),
    signals,
    tier: resolveTier(produced.produces, imported.imports, toolchain.isUsingToolchain),
    isUsingToolchain: toolchain.isUsingToolchain
  };
};
export {
  detectRepoProfile
};
//# sourceMappingURL=detectProfile.mjs.map
