/**
 * Provider activation policy — default off; explicit gating only.
 * See docs/architecture-decisions.md
 */

const WEIGHT_RANK = { light: 0, medium: 1, heavy: 2 };

function readPolicy(matrix) {
  return (
    matrix?.provider_activation_policy || {
      memory_providers: { default: "off", require_doctor_pass: true, allow_on_light: false },
      graph_providers: { default: "off", require_doctor_pass: true, allow_on_light: false }
    }
  );
}

function evaluateActivation({ kind, memoryLevel, overallWeight, capability, matrix, doctorPass, featureFlags = {} }) {
  const policy = readPolicy(matrix);
  const block = policy[kind] || { default: "off" };
  const flagKey = kind === "memory_providers" ? "CAPINT_MEMORY" : "CAPINT_GRAPH";
  const flagOn = featureFlags[kind] || process.env[flagKey] === "1";

  const reasons = [];
  let activated = false;

  if (block.default === "on") {
    activated = true;
    reasons.push("policy_default_on");
  }

  if (memoryLevel === "required") {
    activated = true;
    reasons.push("capability_requires_memory");
  }

  if (flagOn) {
    activated = true;
    reasons.push("feature_flag");
  }

  if (!block.allow_on_light && overallWeight === "light" && memoryLevel !== "required") {
    activated = false;
    reasons.push("blocked_light_weight");
  }

  if (block.require_doctor_pass && !doctorPass && !flagOn) {
    activated = false;
    reasons.push("doctor_not_pass");
  }

  const highRisk = new Set(block.high_risk_capabilities || ["incident-response", "threat-modeling", "memory-retrieval"]);
  if (highRisk.has(capability) && memoryLevel !== "none") {
    activated = true;
    reasons.push("high_risk_capability");
  }

  return {
    kind,
    activated,
    default: block.default || "off",
    reasons,
    fallback: activated ? null : "local"
  };
}

function resolveProviderActivation({ memoryLevel, overallWeight, capability, matrix, doctorPass, featureFlags }) {
  const memory = evaluateActivation({
    kind: "memory_providers",
    memoryLevel,
    overallWeight,
    capability,
    matrix,
    doctorPass,
    featureFlags
  });
  const graph = evaluateActivation({
    kind: "graph_providers",
    memoryLevel: memoryLevel === "required" ? "required" : "optional",
    overallWeight,
    capability,
    matrix,
    doctorPass,
    featureFlags
  });
  return { memory, graph, anyActivated: memory.activated || graph.activated };
}

module.exports = {
  readPolicy,
  evaluateActivation,
  resolveProviderActivation,
  WEIGHT_RANK
};
