import { promises as fs } from 'node:fs';
import path from 'node:path';
import { buildTypesFsPath } from '../../../core/config/index.js';
import { toKebabCase } from './context-analyzer.js';
export async function createTypeDefinition(analysis, sourceFilePath) {
    const domain = extractDomain(sourceFilePath);
    const fileNome = toKebabCase(analysis.typeName);
    const typeCaminho = buildTypesFsPath(path.posix.join(domain, `${fileNome}.ts`));
    const existing = await findExistingType(analysis.typeName);
    if (existing) {
        return `@types/types`;
    }
    const dir = path.dirname(typeCaminho);
    await fs.mkdir(dir, {
        recursive: true
    });
    const content = generateTypeFileContent(analysis, sourceFilePath);
    try {
        await fs.writeFile(typeCaminho, content, { encoding: 'utf-8', flag: 'wx' });
    }
    catch (err) {
        const code = err.code;
        if (code === 'EEXIST') {
            return `@types/types`;
        }
        throw err;
    }
    await addExportToIndex(domain, fileNome);
    return `@types/types`;
}
export async function findExistingType(typeName) {
    try {
        const tiposDir = buildTypesFsPath('');
        const types = await scanTypesDirectory(tiposDir);
        for (const type of types) {
            if (type.name === typeName) {
                return type;
            }
        }
        return null;
    }
    catch {
        return null;
    }
}
export function isSameType(type1, type2) {
    const normalize = (str) => str.replace(/\s+/g, ' ').trim();
    return normalize(type1.definition) === normalize(type2);
}
function generateTypeFileContent(analysis, sourceFilePath) {
    const date = new Date().toISOString();
    return `// SPDX-License-Identifier: MIT
/**
 * Tipo gerado automaticamente
 * Origem: ${sourceFilePath}
 * Confiança: ${analysis.confidence}%
 * Data: ${date}
 *
 * @generated by tutanus fix-any-to-proper-type
 */

${analysis.typeDefinition}
`;
}
async function addExportToIndex(domain, fileNome) {
    const indexCaminho = buildTypesFsPath(path.posix.join(domain, 'index.ts'));
    try {
        const content = await fs.readFile(indexCaminho, 'utf-8');
        const exportStatement = `export * from './${fileNome}.js';`;
        if (content.includes(exportStatement)) {
            return;
        }
        await fs.appendFile(indexCaminho, `${exportStatement}\n`, 'utf-8');
    }
    catch {
        const header = `// SPDX-License-Identifier: MIT
/**
 * Exports do domínio ${domain}
 */

`;
        const exportStatement = `export * from './${fileNome}.js';\n`;
        await fs.writeFile(indexCaminho, header + exportStatement, 'utf-8');
    }
}
function extractDomain(fileCaminho) {
    const match = fileCaminho.match(/src[\\/]([\w-]+)[\\/]/);
    return match ? match[1] : 'shared';
}
async function scanTypesDirectory(dir) {
    const types = [];
    try {
        const entries = await fs.readdir(dir, {
            withFileTypes: true
        });
        for (const entry of entries) {
            const fullCaminho = path.join(dir, entry.name);
            if (entry.isDirectory()) {
                const subTipos = await scanTypesDirectory(fullCaminho);
                types.push(...subTipos);
            }
            else if (entry.name.endsWith('.ts') && entry.name !== 'index.ts') {
                const content = await fs.readFile(fullCaminho, 'utf-8');
                const extractedTipos = extractTypesFromFile(content, fullCaminho);
                types.push(...extractedTipos);
            }
        }
    }
    catch {
    }
    return types;
}
function extractTypesFromFile(content, fileCaminho) {
    const types = [];
    const interfaceRegex = /export\s+interface\s+(\w+)\s*{([^}]*)}/g;
    const typeRegex = /export\s+type\s+(\w+)\s*=\s*([^;]+);/g;
    let match;
    while ((match = interfaceRegex.exec(content)) !== null) {
        types.push({
            name: match[1],
            path: fileCaminho,
            definition: match[0],
            isExported: true,
            domain: extractDomain(fileCaminho)
        });
    }
    while ((match = typeRegex.exec(content)) !== null) {
        types.push({
            name: match[1],
            path: fileCaminho,
            definition: match[0],
            isExported: true,
            domain: extractDomain(fileCaminho)
        });
    }
    return types;
}
//# sourceMappingURL=type-creator.js.map