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

const DEFAULT_PATHS = ["GRAPH_REPORT.md", ".capint/graph/graph.json"];

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 query(rootDir, topic, options = {}) {
  const cfg = options.config || loadProvidersConfig(rootDir);
  const paths = cfg?.graph?.paths || DEFAULT_PATHS;
  const excerpts = [];

  for (const rel of paths) {
    const abs = path.join(rootDir, rel);
    if (!fs.existsSync(abs)) continue;
    const raw = fs.readFileSync(abs, "utf-8");
    if (rel.endsWith(".json")) {
      try {
        const data = JSON.parse(raw);
        excerpts.push({ source: rel, excerpt: JSON.stringify(data).slice(0, 800) });
      } catch {
        excerpts.push({ source: rel, excerpt: raw.slice(0, 800) });
      }
    } else {
      excerpts.push({ source: rel, excerpt: raw.slice(0, 1200) });
    }
  }

  return { driver: "local", topic: topic || null, excerpts, paths_checked: paths };
}

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