import { MultiHopRule } from '../../src/authorization/rules/MultiHopRule.js';
import { describe, it, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import { ValueContext } from '../../src/authorization/ValueContext.js';
import { UnifiedKeyManager } from '../../src/core/UnifiedKeyManager.js';

describe('MultiHopRule', () => {
  let arbiter;
  let multiHopRule;

  beforeEach(() => {
    // Minimal mock Arbiter with relationManager and ValueManager
    arbiter = {
      keyManager: new UnifiedKeyManager(),
      relationManager: {
        getRelationsFromSrc: (id, rel) => {
          if (rel === 'friend' && id === 'alice') {
            return [
              { src: 'alice', dst: 'bob', rel: 'friend', possibility: 0.9, reliability: 0.95 },
              { src: 'alice', dst: 'carol', rel: 'friend', possibility: 0.8, reliability: 0.9 }
            ];
          }
          if (rel === 'friend' && id === 'bob') {
            return [
              { src: 'bob', dst: 'dave', rel: 'friend', possibility: 0.7, reliability: 0.85 }
            ];
          }
          if (rel === 'friend' && id === 'carol') {
            return [
              { src: 'carol', dst: 'dave', rel: 'friend', possibility: 0.6, reliability: 0.8 }
            ];
          }
          return [];
        },
        getAllValueRelationsFromSrc: (id, rel) => {
          return arbiter.relationManager.getRelationsFromSrc(id, rel)
            .filter((relation) => relation.value !== undefined && relation.value !== null);
        },
        getRelationsToDst: () => [],
        getRelationsByName: () => [],
        shouldUseRelationGraphTraversal: () => false,
        valueManager: {
          getBlurredValue: (rel) => ({ interval: { min: rel.value - 5, max: rel.value + 5 }, possibility: rel.possibility || 1.0, reliability: rel.reliability || 1.0 })
        }
      },
      keyByNodeId: new Map([
        ['alice', 'alice'],
        ['bob', 'bob'],
        ['carol', 'carol'],
        ['dave', 'dave']
      ]),
      nodeIdByKey: new Map([
        ['alice', 'alice'],
        ['bob', 'bob'],
        ['carol', 'carol'],
        ['dave', 'dave']
      ]),
      resolveNodeId: (key) => arbiter.nodeIdByKey.get(key),
      resolveKey: (id) => arbiter.keyByNodeId.get(id),
      _getInferenceEngine: () => ({
        estimatePolicyElement: () => ({ outcome: 'negative', totalCases: 0, possibility: 0 })
      })
    };
    arbiter.relationManager.valueManager = arbiter.relationManager.valueManager;
    multiHopRule = new MultiHopRule(arbiter);
  });

  it('returns correct possibility for direct multi-hop path', () => {
    const rule = {
      type: 'multi_hop',
      relation: 'friend',
      maxDepth: 3
    };
    // alice → bob → dave (0.9, 0.7) and alice → carol → dave (0.8, 0.6)
    const valueContext = new ValueContext(arbiter);
    const res = multiHopRule._evaluateRule('alice', 'alice', 'dave', 'dave', rule, {}, null, { collectValues: true, valueContext });
    // Path 1: min(0.9,0.7)=0.7, Path 2: min(0.8,0.6)=0.6, max=0.7
    assert.strictEqual(res.possibility, 0.7);
    assert.ok(Array.isArray(res.collectedValues));
  });

  it('returns 0 possibility if no path exists', () => {
    const rule = {
      type: 'multi_hop',
      relation: 'friend',
      maxDepth: 2
    };
    // No path from dave to alice
    const valueContext = new ValueContext(arbiter);
    const res = multiHopRule._evaluateRule('dave', 'dave', 'alice', 'alice', rule, {}, null, { collectValues: true, valueContext });
    assert.strictEqual(res.possibility, 0);
    assert.ok(Array.isArray(res.collectedValues));
    assert.strictEqual(res.collectedValues.length, 0);
  });

  

  it('aggregates multiple values using interval fusion', () => {
    // Add values to edges
    arbiter.relationManager.getRelationsFromSrc = (id, rel) => {
      if (rel === 'friend' && id === 'alice') {
        return [
          { src: 'alice', dst: 'bob', rel: 'friend', possibility: 0.9, reliability: 0.95, value: 100, changed_last_at: Date.now() },
          { src: 'alice', dst: 'carol', rel: 'friend', possibility: 0.8, reliability: 0.9, value: 200, changed_last_at: Date.now() }
        ];
      }
      if (rel === 'friend' && id === 'bob') {
        return [
          { src: 'bob', dst: 'dave', rel: 'friend', possibility: 0.7, reliability: 0.85, value: 300, changed_last_at: Date.now() }
        ];
      }
      if (rel === 'friend' && id === 'carol') {
        return [
          { src: 'carol', dst: 'dave', rel: 'friend', possibility: 0.6, reliability: 0.8, value: 400, changed_last_at: Date.now() }
        ];
      }
      return [];
    };
    const rule = {
      type: 'multi_hop',
      relation: 'friend',
      maxDepth: 3,
      valueAggregation: 'sum'
    };
    const valueContext = new ValueContext(arbiter);
    const res = multiHopRule._evaluateRule('alice', 'alice', 'dave', 'dave', rule, {}, null, { collectValues: true, valueContext });
    // Two paths with ValueContext contributions from each node in the path.
    // Path 1 collects: edge 100, alice context 100/200, edge 300, bob context 300
    // Interval sum: [95+95+195+295+295, 105+105+205+305+305] = [975,1025]
    // Path 2 collects: edge 200, alice context 100/200, edge 400, carol context 400
    // Interval sum: [95+195+195+395+395, 105+205+205+405+405] = [1275,1325]
    assert.ok(Array.isArray(res.collectedValues));
    assert.strictEqual(res.collectedValues.length, 2);
    const intervals = res.collectedValues.map((cv) => cv.value).sort((a, b) => a.min - b.min);
    assert.deepStrictEqual(intervals[0], { min: 975, max: 1025 });
    assert.deepStrictEqual(intervals[1], { min: 1275, max: 1325 });
  });

  it('filters out values outside TTL', () => {
    arbiter.relationManager.getRelationsFromSrc = (id, rel) => {
      if (rel === 'friend' && id === 'alice') {
        return [
          { src: 'alice', dst: 'bob', rel: 'friend', possibility: 0.9, reliability: 0.95, value: 100, changed_last_at: Date.now() - 2 * 24 * 60 * 60 * 1000 },
          { src: 'alice', dst: 'carol', rel: 'friend', possibility: 0.8, reliability: 0.9, value: 200, changed_last_at: Date.now() - 2 * 24 * 60 * 60 * 1000 }
        ];
      }
      return [];
    };
    const rule = {
      type: 'multi_hop',
      relation: 'friend',
      maxDepth: 1
    };
    const valueContext = new ValueContext(arbiter);
    const res = multiHopRule._evaluateRule('alice', 'alice', 'bob', 'bob', rule, {}, null, { collectValues: true, valueContext });
    assert.ok(Array.isArray(res.collectedValues));
    assert.strictEqual(res.collectedValues.length, 0);
  });
}); 
