import path from 'node:path';
import { normalizePath } from './index.js';
export function normalizarPosix(caminho) {
    return path.posix.normalize(normalizePath(caminho || ''));
}
export function resolverArquivoExistente(caminho, arquivosExistentes) {
    const alvo = normalizarPosix(caminho);
    if (arquivosExistentes.has(alvo))
        return alvo;
    const ext = path.posix.extname(alvo);
    const base = ext ? alvo.slice(0, -ext.length) : alvo;
    if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
        const candidates = [`${base}.ts`, `${base}.tsx`, `${base}.js`, `${base}.mjs`, `${base}.cjs`];
        for (const elem of candidates) {
            const node = normalizarPosix(elem);
            if (arquivosExistentes.has(node))
                return node;
        }
    }
    if (ext === '.jsx') {
        const candidates = [`${base}.tsx`, `${base}.ts`, `${base}.jsx`];
        for (const elem of candidates) {
            const node = normalizarPosix(elem);
            if (arquivosExistentes.has(node))
                return node;
        }
    }
    if (!ext) {
        const candidates = [`${alvo}.ts`, `${alvo}.tsx`, `${alvo}.js`, `${alvo}.jsx`, `${alvo}.mjs`, `${alvo}.cjs`, `${alvo}.d.ts`, `${alvo}/index.ts`, `${alvo}/index.tsx`, `${alvo}/index.js`, `${alvo}/index.mjs`, `${alvo}/index.cjs`];
        for (const elem of candidates) {
            const node = normalizarPosix(elem);
            if (arquivosExistentes.has(node))
                return node;
        }
    }
    return alvo;
}
export function resolverModulo(mod, relPath, arquivosExistentes) {
    if (!mod.startsWith('.') && !mod.startsWith('/')) {
        return {
            key: mod,
            existe: true
        };
    }
    if (mod.startsWith('/')) {
        const absNorm = normalizarPosix(mod);
        if (!arquivosExistentes)
            return {
                key: absNorm,
                existe: true
            };
        const resolved = resolverArquivoExistente(absNorm, arquivosExistentes);
        return {
            key: resolved,
            existe: arquivosExistentes.has(resolved)
        };
    }
    const fromDir = normalizarPosix(path.posix.dirname(normalizarPosix(relPath)));
    const joined = normalizarPosix(path.posix.join(fromDir, mod));
    if (!arquivosExistentes)
        return {
            key: joined,
            existe: true
        };
    const resolved = resolverArquivoExistente(joined, arquivosExistentes);
    return {
        key: resolved,
        existe: arquivosExistentes.has(resolved)
    };
}
export function reescreverImports(conteudo, arquivoDe, arquivoPara) {
    const padrao = /(import\s+[^'";]+from\s*['"]([^'"\n]+)['"]\s*;?|export\s+\*?\s*from\s*['"]([^'"\n]+)['"];?|require\(\s*['"]([^'"\n]+)['"]\s*\))/g;
    const norm = (caminho) => path.posix.normalize(normalizePath(caminho));
    const baseDe = path.posix.dirname(norm(arquivoDe));
    const basePara = path.posix.dirname(norm(arquivoPara));
    const reescritos = [];
    const novoConteudo = conteudo.replace(padrao, (full, _i1, gFrom, gExport, gReq) => {
        const spec = gFrom || gExport || gReq;
        if (!spec)
            return full;
        const isRelative = spec.startsWith('./') || spec.startsWith('../');
        const isAliasRaiz = spec.startsWith('@/');
        const isProjectAlias = /^@(?:analistas|arquitetos|cli|relatorios|tipos|zeladores)\//.test(spec);
        if (!isAliasRaiz && !isProjectAlias && !spec.includes('/src/') && !isRelative)
            return full;
        let alvoAntigo;
        if (isAliasRaiz || isProjectAlias || spec.includes('/src/')) {
            let specNormalized = spec;
            if (isAliasRaiz)
                specNormalized = specNormalized.replace(/^@\//, 'src/');
            else if (isProjectAlias)
                specNormalized = specNormalized.replace(/^@([^/]+)\//, 'src/$1/');
            let afterSrc = specNormalized.replace(/^.*src\//, '');
            afterSrc = afterSrc.replace(/\.js$/, '');
            alvoAntigo = norm(path.posix.join('src', afterSrc || ''));
            alvoAntigo = alvoAntigo.replace(/^src\/cli\/utils\//, 'src/utils/').replace(/^src\/cli\//, 'src/')
                .replace(/^src\/[^/]+\/(?:util|utils)\//, 'src/utils/');
            alvoAntigo = alvoAntigo.replace(/\/utils\/utils\//g, '/utils/');
        }
        else {
            alvoAntigo = norm(path.posix.join(baseDe, spec));
        }
        let novoRel = path.posix.relative(basePara, alvoAntigo);
        novoRel = path.posix.normalize(novoRel);
        if (!novoRel.startsWith('.'))
            novoRel = `./${novoRel}`;
        const originalExt = path.posix.extname(spec);
        if (!originalExt && !path.posix.extname(novoRel) && !novoRel.endsWith('/index')) {
            novoRel += '/index';
        }
        if (originalExt === '.js' || originalExt === '.mjs' || originalExt === '.cjs') {
            if (!novoRel.endsWith(originalExt))
                novoRel += originalExt;
        }
        else if (!path.posix.extname(novoRel)) {
            novoRel += '.js';
        }
        reescritos.push({
            from: spec,
            to: novoRel
        });
        return full.replace(spec, novoRel);
    });
    return {
        novoConteudo,
        reescritos
    };
}
//# sourceMappingURL=imports.js.map