import path from "node:path";
import { parseManifestFully } from "./_manifest-ast.js";

/**
 * Reads a feature.manifest.ts and returns { name, requiredCores }.
 * Backed by the AST parser from _manifest-ast.js — no longer uses regex.
 *
 * Returns: { name: string, requiredCores: string[] } | null
 */
export function readManifestSource(manifestPath) {
  const full = parseManifestFully(manifestPath);
  if (!full) return null;
  return { name: full.name, requiredCores: full.requiredCores };
}

/**
 * Canonical manifest path for a given feature package root.
 */
export function manifestPathForFeature(featureRoot) {
  return path.join(featureRoot, "src", "feature.manifest.ts");
}

/**
 * Given an absolute file path and the monorepo root, returns the feature
 * package root that contains the file (e.g. /repo/packages/auth). Returns
 * null when the file lives outside the packages/ tree.
 *
 * Assumes the conventional layout `packages/<feature>/src/...`.
 */
export function featureRootForFile(filepath, repoRoot) {
  const packagesDir = path.join(repoRoot, "packages");
  if (!filepath.startsWith(packagesDir + path.sep)) return null;
  const rel = filepath.slice(packagesDir.length + 1); // e.g. "auth/src/..."
  const slash = rel.indexOf(path.sep);
  if (slash === -1) return null;
  const featureName = rel.slice(0, slash);
  return path.join(packagesDir, featureName);
}
