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;

  return {
    code: rawCode,
    digits,
    type,
    version,
    key: `${rawCode}.${type}`,
    routingGroup,
  };
}

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`,
    };
  }

  return { destination: candidates[0], 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 };
