'use strict';

/**
 * tool-labels.js — Pattern-matching tool name -> label resolver.
 *
 * Resolution order:
 *   1. Exact match (e.g. "exec" -> "Running command...")
 *   2. Prefix match (e.g. "camofox_*" -> "Using browser...")
 *   3. Regex match (e.g. /^claude_/ -> "Running Claude Code...")
 *   4. Default label ("Working...")
 */

const path = require('path');
const fs = require('fs');

let _labels = null;
let _externalFile = null;

/**
 * Load tool labels from JSON file(s).
 * Merges external override on top of built-in defaults.
 * @param {string|null} externalFile - Path to external JSON override
 */
function loadLabels(externalFile = null) {
  _externalFile = externalFile;

  // Load built-in defaults
  const builtinPath = path.join(__dirname, 'tool-labels.json');
  let builtin = {};
  try {
    // eslint-disable-next-line security/detect-non-literal-fs-filename
    builtin = JSON.parse(fs.readFileSync(builtinPath, 'utf8'));
  } catch (_e) {
    /* use empty defaults if file missing */
  }

  let external = {};
  if (externalFile) {
    try {
      // eslint-disable-next-line security/detect-non-literal-fs-filename
      external = JSON.parse(fs.readFileSync(externalFile, 'utf8'));
    } catch (_e) {
      /* external file missing or invalid — use built-in only */
    }
  }

  // Merge: external overrides built-in
  _labels = {
    exact: Object.assign({}, builtin.exact || {}, external.exact || {}),
    prefix: Object.assign({}, builtin.prefix || {}, external.prefix || {}),
    regex: [...(builtin.regex || []), ...(external.regex || [])],
    default: external.default !== undefined ? external.default : builtin.default || 'Working...',
  };

  return _labels;
}

/**
 * Resolve a tool name to a human-readable label.
 * @param {string} toolName
 * @returns {string}
 */
function resolve(toolName) {
  if (!_labels) loadLabels(_externalFile);

  const labels = _labels;

  // 1. Exact match
  if (Object.prototype.hasOwnProperty.call(labels.exact, toolName)) {
    return labels.exact[toolName]; // eslint-disable-line security/detect-object-injection
  }

  // 2. Prefix match
  for (const [prefix, label] of Object.entries(labels.prefix)) {
    if (toolName.startsWith(prefix)) {
      return label;
    }
  }

  // 3. Regex match (patterns stored as strings like "/^claude_/i")
  for (const entry of labels.regex || []) {
    const pattern = typeof entry === 'string' ? entry : entry.pattern;
    const label = typeof entry === 'string' ? labels.default : entry.label;
    if (pattern) {
      try {
        const match = pattern.match(/^\/(.+)\/([gimuy]*)$/);
        if (match) {
          const re = new RegExp(match[1], match[2]); // eslint-disable-line security/detect-non-literal-regexp
          if (re.test(toolName)) return label;
        }
      } catch (_e) {
        /* invalid regex — skip */
      }
    }
  }

  // 4. Default
  return labels.default;
}

/**
 * Reset labels (for tests).
 */
function resetLabels() {
  _labels = null;
  _externalFile = null;
}

module.exports = { loadLabels, resolve, resetLabels };
