import { execFile as _execFile } from 'node:child_process';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { messages } from '../core/messages/index.js';
function execFileAsync(cmd, args, opts = {}) {
    return new Promise((resolve, reject) => {
        _execFile(cmd, args, {
            shell: false,
            ...opts
        }, (err, stdout, stderr) => {
            if (err)
                return reject(Object.assign(err, {
                    stdout,
                    stderr
                }));
            resolve({
                stdout: String(stdout || ''),
                stderr: String(stderr || '')
            });
        });
    });
}
const defaultDisclaimerCaminho = 'docs/partials/AVISO-PROVENIENCIA.md';
const marker = /Proveni[eê]ncia e Autoria/i;
async function listMarkdown(root) {
    try {
        const { stdout } = await execFileAsync('git', ['ls-files', '*.md'], {
            cwd: root
        });
        return stdout.split(/\r?\n/).map(string => string.trim()).filter(Boolean);
    }
    catch {
        const out = [];
        async function walk(dir) {
            const entries = await fs.readdir(dir, {
                withFileTypes: true
            });
            for (const erro of entries) {
                const caminho = path.join(dir, erro.name);
                if (erro.isDirectory()) {
                    if (/^(node_modules|dist|\.git|pre-public|preview-tutanus|coverage|relatorios|\.tutanus)$/i.test(erro.name))
                        continue;
                    out.push(...(await walk(caminho)));
                }
                else if (/\.md$/i.test(erro.name)) {
                    out.push(path.relative(root, caminho));
                }
            }
            return out;
        }
        return walk(root);
    }
}
export async function addDisclaimer({ root = process.cwd(), disclaimerPath = defaultDisclaimerCaminho, dryRun = false } = {}) {
    const absDisclaimer = path.join(root, disclaimerPath);
    const disclaimerText = await fs.readFile(absDisclaimer, 'utf8').catch(() => {
        throw new Error(messages.LicensasMensagens.disclaimerNaoEncontrado(disclaimerPath));
    });
    const files = (await listMarkdown(root)).filter(arquivo => arquivo !== disclaimerPath && !arquivo.startsWith('pre-public/')).filter(arquivo => !arquivo.startsWith('.abandonados/') && !arquivo.startsWith('.deprecados/') && !arquivo.startsWith('coverage/') && !arquivo.startsWith('relatorios/'));
    const updatedArquivos = [];
    for (const rel of files) {
        const abs = path.join(root, rel);
        const content = await fs.readFile(abs, 'utf8').catch(() => null);
        if (content === null)
            continue;
        const head = content.split('\n').slice(0, 30).join('\n');
        if (marker.test(head))
            continue;
        const updated = `${disclaimerText}\n\n${content.trimStart()}\n`;
        if (!dryRun)
            await fs.writeFile(abs, updated, 'utf8');
        updatedArquivos.push(rel);
    }
    return {
        updatedArquivos
    };
}
export async function verifyDisclaimer({ root = process.cwd(), disclaimerPath = defaultDisclaimerCaminho } = {}) {
    const files = (await listMarkdown(root)).filter(arquivo => arquivo !== disclaimerPath && !arquivo.startsWith('pre-public/') && !arquivo.startsWith('preview-tutanus/')).filter(arquivo => !arquivo.startsWith('.abandonados/') && !arquivo.startsWith('.deprecados/') && !arquivo.startsWith('coverage/') && !arquivo.startsWith('relatorios/'));
    const missing = [];
    for (const rel of files) {
        const abs = path.join(root, rel);
        const content = await fs.readFile(abs, 'utf8').catch(() => null);
        if (content === null)
            continue;
        const head = content.split('\n').slice(0, 30).join('\n');
        if (!marker.test(head))
            missing.push(rel);
    }
    return {
        missing
    };
}
export const disclaimerModule = {
    addDisclaimer,
    verifyDisclaimer
};
//# sourceMappingURL=disclaimer.js.map