const fs = require("fs");
const path = require("path");
const { resolveProviderActivation } = require("./providers/activation-policy");
const { createMemoryProviderStub } = require("./providers/memory-provider");
const { createGraphProviderStub } = require("./providers/graph-provider");
const { buildLocalContextPack } = require("./context-pack");
const { search: localMemorySearch } = require("./providers/local-memory-adapter");
const { query: localGraphQuery } = require("./providers/local-graph-adapter");

function doctorPassQuick(rootDir) {
  const matrixPath = path.join(rootDir, "skill-routing-matrix.json");
  const registryPath = path.join(rootDir, "registry.json");
  if (!fs.existsSync(matrixPath) || !fs.existsSync(registryPath)) return false;
  try {
    JSON.parse(fs.readFileSync(matrixPath, "utf-8"));
    JSON.parse(fs.readFileSync(registryPath, "utf-8"));
    return true;
  } catch {
    return false;
  }
}

function localContextEnabled(featureFlags) {
  if (featureFlags?.local_context === true) return true;
  return process.env.CAPINT_LOCAL_CONTEXT === "1";
}

function resolveMemoryStrategy({ intent, routeResult, matrix, rootDir, featureFlags }) {
  const requiresMemory = routeResult.taskTypeResolved?.requires_memory || "optional";
  const highRiskCapabilities = new Set(["incident-response", "threat-modeling", "memory-retrieval"]);
  const hasOverrideSignals = Boolean(intent?.overrides?.workflow || intent?.overrides?.skill);

  let memory = requiresMemory;
  if (requiresMemory === "none") memory = "none";
  else if (requiresMemory === "required") memory = "required";
  else if (highRiskCapabilities.has(routeResult?.taskTypeResolved?.capability) || hasOverrideSignals) {
    memory = "required";
  } else memory = "optional";

  const doctorPass = rootDir ? doctorPassQuick(rootDir) : false;
  const providerActivation = resolveProviderActivation({
    memoryLevel: memory,
    overallWeight: routeResult.overall,
    capability: routeResult?.taskTypeResolved?.capability || null,
    matrix,
    doctorPass,
    featureFlags
  });

  const providers = {
    memory: providerActivation.memory.activated ? createMemoryProviderStub("memory-adapter") : createMemoryProviderStub("local"),
    graph: providerActivation.graph.activated ? createGraphProviderStub("graph-adapter") : createGraphProviderStub("local")
  };

  const context_pack = buildLocalContextPack({
    rootDir: rootDir || process.cwd(),
    memoryLevel: memory,
    providerActivated: providerActivation.anyActivated
  });

  let local_adapters = null;
  if (localContextEnabled(featureFlags) && rootDir) {
    local_adapters = {
      memory: localMemorySearch(rootDir, intent?.rawText || ""),
      graph: localGraphQuery(rootDir, routeResult?.taskTypeResolved?.capability || null)
    };
  }

  return {
    memory,
    provider_activation: providerActivation,
    providers_stub: { memory: providers.memory.name, graph: providers.graph.name },
    context_pack,
    local_adapters,
    events: [
      {
        type: "route.intent_resolved",
        capability: routeResult?.taskTypeResolved?.capability || null,
        memory,
        providers_activated: providerActivation.anyActivated,
        local_context: Boolean(local_adapters)
      }
    ]
  };
}

module.exports = { resolveMemoryStrategy, doctorPassQuick, localContextEnabled };
