/**
 * Origin-file discovery and path conversion. Pure domain — no UI, no
 * prompts, no logging. Side effects limited to node:fs.
 *
 * The .origin convention mirrors src/generator/engine/file-writer.ts:
 *   path.replace(/\.(?=[^.]*$)/, '.origin.')
 * which inserts `.origin` immediately before the final extension segment
 * (e.g. `foo.ts` → `foo.origin.ts`; `bar.module.ts` → `bar.module.origin.ts`).
 */
import * as fs from 'node:fs';
import path from 'node:path';
const ORIGIN_INSERT_RE = /\.(?=[^.]*$)/;
const ORIGIN_DETECT_RE = /\.origin\.[^./\\]+$/;
export function toOriginPath(currentPath) {
    if (!ORIGIN_INSERT_RE.test(currentPath))
        return currentPath;
    return currentPath.replace(ORIGIN_INSERT_RE, '.origin.');
}
export function toCurrentPath(originPath) {
    return originPath.replace('.origin.', '.');
}
export function isOriginPath(p) {
    return ORIGIN_DETECT_RE.test(p);
}
export function discoverOrigins(pathspec, baseDir = process.cwd()) {
    const root = pathspec ?? baseDir;
    const stat = safeStat(root);
    if (!stat)
        return [];
    if (stat.isFile()) {
        const current = isOriginPath(root) ? toCurrentPath(root) : root;
        const origin = toOriginPath(current);
        if (!fs.existsSync(origin))
            return [];
        return [
            { current: rel(current, baseDir), origin: rel(origin, baseDir) },
        ];
    }
    return walk(root, baseDir);
}
function walk(dir, baseDir) {
    const out = [];
    const entries = fs.readdirSync(dir, { withFileTypes: true });
    for (const entry of entries) {
        const full = path.join(dir, entry.name);
        if (entry.isDirectory()) {
            out.push(...walk(full, baseDir));
            continue;
        }
        if (entry.isFile() && isOriginPath(full)) {
            const current = toCurrentPath(full);
            out.push({
                current: rel(current, baseDir),
                origin: rel(full, baseDir),
            });
        }
    }
    return out;
}
function safeStat(p) {
    try {
        return fs.statSync(p);
    }
    catch {
        return null;
    }
}
function rel(absOrRel, baseDir) {
    const abs = path.isAbsolute(absOrRel)
        ? absOrRel
        : path.resolve(baseDir, absOrRel);
    return path.relative(baseDir, abs);
}
