/**
 * Troubleshoot Index Search
 * Searches the troubleshooting-index.json for matching problems
 */

import { readFileSync, existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

/**
 * Load the troubleshooting index
 * @returns {Object} The index object or null if not found
 */
export function loadIndex() {
  const indexPath = join(__dirname, '../../framework/index/troubleshooting-index.json');

  if (!existsSync(indexPath)) {
    return null;
  }

  try {
    const content = readFileSync(indexPath, 'utf-8');
    return JSON.parse(content);
  } catch (error) {
    console.error('Error loading troubleshooting index:', error.message);
    return null;
  }
}

/**
 * Calculate relevance score for a problem based on keywords
 * @param {Object} problem - The problem object from index
 * @param {string[]} searchTerms - Search terms from user
 * @returns {number} Relevance score (higher is better)
 */
function calculateScore(problem, searchTerms) {
  let score = 0;
  const searchLower = searchTerms.map(t => t.toLowerCase());

  // Check keywords
  for (const keyword of problem.keywords) {
    const keywordLower = keyword.toLowerCase();
    for (const term of searchLower) {
      if (keywordLower.includes(term) || term.includes(keywordLower)) {
        score += 10;
      }
    }
  }

  // Check title
  const titleLower = problem.title.toLowerCase();
  for (const term of searchLower) {
    if (titleLower.includes(term)) {
      score += 5;
    }
  }

  // Check error pattern (regex match on search string)
  if (problem.errorPattern) {
    try {
      const regex = new RegExp(problem.errorPattern, 'i');
      const searchString = searchTerms.join(' ');
      if (regex.test(searchString)) {
        score += 20; // High score for error pattern match
      }
    } catch (e) {
      // Invalid regex, skip
    }
  }

  // Boost critical severity
  if (problem.severity === 'critical') {
    score *= 1.2;
  }

  return score;
}

/**
 * Search the index for problems matching the keywords
 * @param {string[]} keywords - Search keywords
 * @param {Object} options - Search options
 * @param {string} options.category - Filter by category
 * @returns {Object[]} Array of matching problems with scores
 */
export function searchIndex(keywords, options = {}) {
  const index = loadIndex();

  if (!index || !index.problems) {
    return [];
  }

  let problems = index.problems;

  // Filter by category if specified
  if (options.category) {
    problems = problems.filter(p => p.category === options.category);
  }

  // Score and filter problems
  const results = problems
    .map(problem => ({
      ...problem,
      score: calculateScore(problem, keywords)
    }))
    .filter(p => p.score > 0)
    .sort((a, b) => b.score - a.score);

  return results;
}

/**
 * Get all categories from the index
 * @returns {Object} Categories object
 */
export function getCategories() {
  const index = loadIndex();
  return index?.categories || {};
}

/**
 * Get a specific problem by ID
 * @param {string} id - Problem ID
 * @returns {Object|null} Problem object or null
 */
export function getProblemById(id) {
  const index = loadIndex();

  if (!index || !index.problems) {
    return null;
  }

  return index.problems.find(p => p.id === id) || null;
}

export default {
  loadIndex,
  searchIndex,
  getCategories,
  getProblemById
};
