// lib/mines/taxonomy.js
//
// Pure taxonomy helpers for the Mines module. No DB dependency — safe to
// import in any context including tests, edge functions, and client bundles.

/**
 * Canonical ordered list of document categories used by mines_source_documents.
 * The CHECK constraint in schema.js mirrors this list exactly.
 */
export const DOCUMENT_CATEGORIES = [
  '00_historic',
  '01_arcgis_data',
  '02_assay_labs',
  '03_cad_files',
  '04_official_database',
  '05_drill_campaign',
  '06_exploration_geos',
  '07_geophysics',
  '08_backup_bd',
  '09_petrography',
  '10_presentations',
  '11_general_pictures',
  '12_safety',
  '13_reports',
  '14_inegi_data',
  '15_sgm_data',
  '16_claims_properties',
  '17_minesight',
  '18_exported_maps',
  '19_survey',
  '20_geotechnical',
  '21_general_files',
  '22_qa_qc',
  'uncategorized',
];

// Build a lookup map from 2-digit prefix string → canonical category name.
// e.g. { '00': '00_historic', '01': '01_arcgis_data', ... }
const PREFIX_MAP = Object.create(null);
for (const cat of DOCUMENT_CATEGORIES) {
  const m = cat.match(/^(\d{2})_/);
  if (m) PREFIX_MAP[m[1]] = cat;
}

/**
 * Classify a file path into a DOCUMENT_CATEGORIES entry by inspecting each
 * path segment for a leading two-digit number prefix (e.g. "13_reports",
 * "13-Reports", "13 Reports").
 *
 * Rules:
 *  - Splits on both '/' and '\' to handle Windows and Unix paths.
 *  - Tests every segment with regex /^(\d{2})[-_ ]/i (case-insensitive).
 *  - When multiple segments match, the DEEPEST (rightmost) match wins —
 *    it is the most specific category in the hierarchy.
 *  - Safely handles Unicode / accented Spanish characters (no regex on the
 *    full segment text; only tests the ASCII prefix).
 *  - Returns 'uncategorized' when no segment matches a known prefix.
 *
 * @param {string} filePath  — any file path string (absolute or relative)
 * @returns {string}         — a member of DOCUMENT_CATEGORIES
 */
export function classifyByFolderPath(filePath) {
  // Split on both forward and back slashes; filter empty segments.
  const segments = String(filePath || '').split(/[/\\]/).filter(Boolean);

  let matched = null;

  for (const segment of segments) {
    // Test for a leading 2-digit number followed by a separator character.
    // We only inspect the first 4 bytes so accented chars later in the
    // segment name never cause issues.
    const m = segment.match(/^(\d{2})[-_ ]/i);
    if (!m) continue;
    const prefix = m[1]; // e.g. '13'
    if (Object.prototype.hasOwnProperty.call(PREFIX_MAP, prefix)) {
      // Keep iterating — deepest match wins.
      matched = PREFIX_MAP[prefix];
    }
  }

  return matched ?? 'uncategorized';
}
