import { SimpleGraph } from '../graph/SimpleGraph.js';

export class RelationGraphTraversal {
  constructor(manager) {
    this.manager = manager;
    this.enabled = !!manager.arbiter.options?.useRelationGraphTraversal;
    this.minDegree = Number.isFinite(manager.arbiter.options?.relationGraphMinDegree)
      ? manager.arbiter.options.relationGraphMinDegree
      : 800;
    this.byName = new Map();
  }

  getGraph(relation) {
    if (!this.enabled) return null;
    let graph = this.byName.get(relation);
    if (!graph) {
      graph = new SimpleGraph({ directed: true });
      this.byName.set(relation, graph);
    }
    return graph;
  }

  addRelation(srcId, relation, dstId) {
    const graph = this.getGraph(relation);
    if (!graph) return;
    graph.addEdge(srcId, dstId);
  }

  removeRelation(srcId, relation, dstId) {
    const graph = this.getGraph(relation);
    if (!graph) return;
    graph.removeEdge(srcId, dstId);
  }

  getNeighbors(nodeId, relation, reverse = false) {
    const graph = this.getGraph(relation);
    if (!graph) return null;
    return graph.neighbors(nodeId, reverse);
  }

  shouldUseTraversal(nodeId, relation, reverse = false) {
    if (!this.enabled) return false;
    const graph = this.getGraph(relation);
    if (!graph) return false;
    const degree = graph.degree(nodeId, reverse);
    if (degree < this.minDegree) return false;
    this.minDegree = Math.max(this.minDegree, Math.floor(degree * 0.9));
    return true;
  }

  clear() {
    this.byName.clear();
  }
}
