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

const DEFAULT_PATHS = ["HANDOFF.md", "design.md", "AGENT.md", ".capint/rules/core.md"];

function loadProvidersConfig(rootDir) {
  const p = path.join(rootDir, ".capint", "providers.json");
  if (!fs.existsSync(p)) return null;
  try {
    return JSON.parse(fs.readFileSync(p, "utf-8"));
  } catch {
    return null;
  }
}

function search(rootDir, query, options = {}) {
  const cfg = options.config || loadProvidersConfig(rootDir);
  const paths = cfg?.memory?.paths || DEFAULT_PATHS;
  const q = (query || "").toLowerCase();
  const hits = [];

  for (const rel of paths) {
    const abs = path.join(rootDir, rel);
    if (!fs.existsSync(abs)) continue;
    const text = fs.readFileSync(abs, "utf-8");
    const lines = text.split("\n");
    for (let i = 0; i < lines.length; i++) {
      if (!q || lines[i].toLowerCase().includes(q)) {
        hits.push({
          source: rel,
          line: i + 1,
          excerpt: lines[i].trim().slice(0, 200)
        });
      }
    }
  }

  return { driver: "local", query, hits: hits.slice(0, 20), paths_checked: paths };
}

module.exports = { search, loadProvidersConfig, DEFAULT_PATHS };
