const path = require('path'); function normalizeCadType(ext) { return String(ext || '').toLowerCase(); } function getCadInfo(filename) { const baseName = path.basename(filename); const match = baseName.match(/^(.*)\.(prt|asm|drw)(?:\.([^.]+))?$/i); if (!match) { return null; } const rawCode = match[1]; const type = normalizeCadType(match[2]); const version = match[3] || ''; const digits = rawCode.replace(/\D/g, ''); const routingGroup = digits.length >= 5 ? digits.slice(2, 5) : null; const subfolder = digits.length >= 2 ? (digits[1] === '1' ? 'A' : digits[1] === '2' ? 'M_B' : null) : null; return { code: rawCode, digits, type, version, key: `${rawCode}.${type}`, routingGroup, subfolder, }; } function getDestinationDecision(filename, config, destinationIndex) { const cadInfo = getCadInfo(filename); if (!cadInfo) { return { destination: null, reason: 'Nessuna regola trovata' }; } if (!cadInfo.routingGroup) { return { destination: null, reason: 'Nome file non conforme: servono almeno 5 cifre nel nome per ricavare la 3a-4a-5a cifra', }; } const group = cadInfo.routingGroup; const candidates = destinationIndex?.get(group) || []; if (!candidates.length) { return { destination: null, reason: `Sottocartella ${group} non trovata nella destinazione`, }; } if (candidates.length > 1) { return { destination: null, reason: `Sottocartella ${group} trovata in ${candidates.length} percorsi diversi`, }; } if (!cadInfo.subfolder) { return { destination: null, reason: `Prefisso non riconosciuto (${cadInfo.digits[1]}): atteso 91 (→ A) o 92 (→ M_B)`, }; } return { destination: path.join(candidates[0], cadInfo.subfolder), reason: null }; } function findDestination(filename, config, destinationIndex) { return getDestinationDecision(filename, config, destinationIndex).destination; } function isCadFile(filename) { return Boolean(getCadInfo(filename)); } module.exports = { findDestination, getDestinationDecision, isCadFile, getCadInfo };