/**
 * HLDP-ZY://native-repo/module/step-5
 * 光湖原生数据库 · 第5步 · ripgrep搜索模块
 *
 * @chain: D118 · 2026-05-31
 * @module: hldp-search
 * @step: 第5步 / 共8步
 * @deploy: BS-SG-002
 *
 * hldpSearch(query) → rg 执行 → HLDP格式返回
 * 输入: query 字符串
 * 输出: [{ file, line, content }]
 */

const { execSync } = require('child_process');
const { NATIVE_DIR } = require('./step-2-git-init');

function hldpSearch(query) {
  try {
    const result = execSync(
      `rg -n --no-heading -M 200 "${query.replace(/[$"\\]/g, '\\$&')}" ${NATIVE_DIR} --glob '!.git' --glob '!node_modules' 2>/dev/null`,
      { encoding: 'utf8', timeout: 10000, maxBuffer: 1024 * 1024 }
    );

    if (!result.trim()) return { ok: true, query, count: 0, results: [] };

    const results = result.trim().split('\n').slice(0, 50).map(line => {
      const [file, lnum, ...rest] = line.split(':');
      return {
        file: file.replace(NATIVE_DIR + '/', ''),
        line: parseInt(lnum),
        content: rest.join(':').trim(),
      };
    });

    return { ok: true, query, count: results.length, results };
  } catch (e) {
    if (e.status === 1) return { ok: true, query, count: 0, results: [] };
    return { ok: false, error: e.message };
  }
}

module.exports = { hldpSearch };
