import { existsSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
// Subdirectories to look for at each walk level. Order matters: a bundled
// `migration-templates/app-fullstack` beats the monorepo workspace copy
// so a published CLI/plugin does not silently fall back to a sibling
// checkout if both happen to exist (e.g. when running tests from source
// after `pnpm build`).
const CANDIDATE_SUBPATHS = [
    "migration-templates/app-fullstack",
    "packages/demo-apps/app-fullstack",
];
// How far up the filesystem to walk. 12 comfortably covers the deepest
// real layout we have today (bundled CLI dist nested inside
// `/.npm-global/lib/node_modules/@superblocksteam/cli/dist/...`) while
// still failing fast on a malformed FS.
const MAX_WALK_HOPS = 12;
/**
 * Absolute path to the bundled `app-fullstack` template tree that the
 * v2 -> v3 migration lays down locally before asking the server to flip
 * `application_v2.template_name`.
 *
 * Resolution walks up from the compiled module's directory and at each
 * level checks two candidates:
 *   1. `migration-templates/app-fullstack` -- the bundled location
 *      populated by
 *      `packages/vite-plugin-file-sync/scripts/copy-migration-templates.mjs`
 *      and by the CLI's own post-esbuild copy step. This is what the
 *      published packages rely on.
 *   2. `packages/demo-apps/app-fullstack` -- the monorepo dev fallback
 *      used when tests run from source (tsx/vitest) before a bundled
 *      copy exists.
 *
 * The walk handles several layouts without special-casing:
 *   - `<pkg>/dist/migration/get-fullstack-template-dir.js` (plugin's
 *     own compiled output) finds the bundled tree one level up.
 *   - `<cli>/dist/chunk-XYZ.js` (esbuild-bundled into the CLI) finds
 *     the bundled tree in the same dir, because the CLI build copies
 *     it into `<cli>/dist/migration-templates/app-fullstack`.
 *   - `<repo>/packages/.../src/migration/get-fullstack-template-dir.ts`
 *     (tsx dev run) walks up to `<repo>` and finds the workspace copy.
 *
 * Throws if no candidate exists -- the restructure module cannot
 * proceed without a template and it is better to fail here with a clear
 * error than to half-migrate an app.
 */
export function getFullstackTemplateDir() {
    const hereDir = dirname(fileURLToPath(import.meta.url));
    const resolved = findFullstackTemplate(hereDir);
    if (resolved)
        return resolved;
    const searched = enumerateSearchedPaths(hereDir);
    throw new Error(`Could not locate the app-fullstack migration template. Searched (in order):\n${searched
        .map((p) => `  - ${p}`)
        .join("\n")}\nRun 'pnpm --filter @superblocksteam/vite-plugin-file-sync build' and, for the published CLI, 'pnpm --filter @superblocksteam/cli build' to populate a bundled copy, or make sure packages/demo-apps/app-fullstack is checked out.`);
}
/**
 * Pure lookup: walk up from `startDir` and return the first existing
 * candidate. Exported for tests so we can drive the walk against a
 * synthetic filesystem without mocking `import.meta.url`.
 */
export function findFullstackTemplate(startDir) {
    let current = startDir;
    for (let hops = 0; hops < MAX_WALK_HOPS; hops++) {
        for (const sub of CANDIDATE_SUBPATHS) {
            const candidate = join(current, sub);
            if (isUsableDir(candidate))
                return candidate;
        }
        const parent = dirname(current);
        if (parent === current)
            break;
        current = parent;
    }
    return null;
}
function enumerateSearchedPaths(startDir) {
    const paths = [];
    let current = startDir;
    for (let hops = 0; hops < MAX_WALK_HOPS; hops++) {
        for (const sub of CANDIDATE_SUBPATHS) {
            paths.push(join(current, sub));
        }
        const parent = dirname(current);
        if (parent === current)
            break;
        current = parent;
    }
    return paths;
}
function isUsableDir(dirPath) {
    try {
        return existsSync(dirPath) && statSync(dirPath).isDirectory();
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=get-fullstack-template-dir.js.map