/**
 * rigor/manager-index-parity.test.js — js-rigor property tests for the
 * RelationManager lookup layer vs the GraphIndices ground truth.
 *
 * RelationManager.getRelationsFromSrc/ToDst consult the RF-08 lookup
 * caches (relationLookupCache/valueLookupCache); GraphIndices holds the
 * ground truth. The two must agree after every mutation — a divergence
 * means a lookup cache went stale.
 *
 * Properties verified:
 *
 *   - LOOKUP PARITY: after every add/remove/overwrite, both layers return
 *     identical (src, dst, possibility) sets for every node/relation pair.
 *   - COUNT CONSISTENCY: relations.length equals the number of distinct
 *     tuples across all index lookups.
 */
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { rigor } from '@rigor/core';
import { Arbiter } from '../../src/index.js';

const POS = [0, 0.25, 0.5, 0.75, 1];
const NODES = ['user:alice', 'mid:1', 'mid:2', 'doc:1'];
const RELS = ['r1', 'r2'];

function fail(message) {
  throw new Error(message);
}

function mulberry32(seed) {
  let a = seed >>> 0;
  return {
    next() {
      a |= 0; a = (a + 0x6D2B79F5) | 0;
      let t = Math.imul(a ^ (a >>> 15), 1 | a);
      t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
      return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
    }
  };
}

const EDGE_UNIVERSE = {
  r1: [
    ['user:alice', 'mid:1'],
    ['mid:1', 'user:alice'],
    ['mid:1', 'mid:2'],
    ['doc:1', 'mid:2'],
    ['mid:2', 'doc:1']
  ],
  r2: [
    ['mid:1', 'doc:1'],
    ['doc:1', 'mid:1'],
    ['mid:2', 'user:alice'],
    ['user:alice', 'mid:2'],
    ['user:alice', 'doc:1'],
    ['mid:2', 'mid:1']
  ]
};

function sig(rels) {
  return rels.map(r => [r.src, r.dst, r.possibility]).sort((x, y) => x[0] - y[0] || x[1] - y[1]).map(x => x.join('|')).join(';');
}

function verifyAllLookups(arb, tag) {
  for (const rel of RELS) {
    for (const node of NODES) {
      const srcId = arb.resolveNodeId(node);
      if (srcId === undefined) continue;
      const managerFrom = arb.relationManager.getRelationsFromSrc(srcId, rel);
      const indexFrom = arb.indices.getRelationsFromSrc(srcId, rel);
      const s1 = sig(managerFrom);
      const s2 = sig(indexFrom);
      if (s1 !== s2) {
        fail(`${tag} fromSrc(${node}, ${rel}) mismatch: manager=[${s1}] index=[${s2}]`);
      }
      const managerTo = arb.relationManager.getRelationsToDst(srcId, rel);
      const indexTo = arb.indices.getRelationsToDst(srcId, rel);
      const t1 = sig(managerTo);
      const t2 = sig(indexTo);
      if (t1 !== t2) {
        fail(`${tag} toDst(${node}, ${rel}) mismatch: manager=[${t1}] index=[${t2}]`);
      }
    }
  }
}

function verifyCount(arb, edges, tag) {
  const n = arb.relations.length;
  if (n !== edges.length) {
    fail(`${tag} relations.length=${n} expected=${edges.length}`);
  }
}

function buildArbiter() {
  const arb = new Arbiter();
  for (const k of NODES) arb.addNode(k, k.startsWith('user') ? 'user' : k.startsWith('mid') ? 'mid' : 'doc');
  for (const r of RELS) arb.setRelationConfig(r, { type: 'direct' });
  return arb;
}

describe('Manager vs index lookup parity (rigor)', () => {
  it('LOOKUP PARITY + COUNT CONSISTENCY through random mutation sequences', async () => {
    async function check({ seed, mutations }) {
      const rng = mulberry32(seed);
      const edges = [];
      const arb = buildArbiter();

      // Initial random edges
      for (const rel of RELS) {
        for (const [src, dst] of EDGE_UNIVERSE[rel]) {
          if (rng.next() < 0.5) {
            const p = POS[Math.floor(rng.next() * POS.length)];
            arb.addRelation(src, rel, dst, { possibility: p });
            edges.push([src, rel, dst, p]);
          }
        }
      }
      verifyAllLookups(arb, 'initial');
      verifyCount(arb, edges, 'initial');

      for (let i = 0; i < mutations; i++) {
        const rel = RELS[Math.floor(rng.next() * 2)];
        const [src, dst] = EDGE_UNIVERSE[rel][Math.floor(rng.next() * EDGE_UNIVERSE[rel].length)];
        const idx = edges.findIndex(e => e[0] === src && e[1] === rel && e[2] === dst);
        if (idx !== -1) {
          arb.removeRelation(src, rel, dst);
          edges.splice(idx, 1);
        } else {
          const p = POS[Math.floor(rng.next() * POS.length)];
          arb.addRelation(src, rel, dst, { possibility: p });
          edges.push([src, rel, dst, p]);
        }
        verifyAllLookups(arb, `mutation ${i}`);
        verifyCount(arb, edges, `mutation ${i}`);
      }

      // Overwrite storm: same tuple 5 times, then lookups must show the last value once
      const [src, dst] = ['user:alice', 'mid:1'];
      for (let i = 0; i < 5; i++) {
        const p = POS[Math.floor(rng.next() * POS.length)];
        arb.addRelation(src, 'r1', dst, { possibility: p });
      }
      const uid = arb.resolveNodeId(src);
      const fromManager = arb.relationManager.getRelationsFromSrc(uid, 'r1');
      const fromIndex = arb.indices.getRelationsFromSrc(uid, 'r1');
      const count = fromIndex.filter(r => r.dst === arb.resolveNodeId(dst)).length;
      if (count !== 1) {
        fail(`overwrite storm left ${count} tuples in index`);
      }
      if (sig(fromManager) !== sig(fromIndex)) {
        fail(`overwrite storm desynced manager vs index`);
      }
      return { edges: edges.length };
    }

    const report = await rigor.campaign(
      [
        rigor.fn('check', check, rigor.args(
          rigor.gen.object({
            seed: rigor.gen.int(1, 100000),
            mutations: rigor.gen.int(3, 10)
          })
        ))
      ],
      rigor.crucible([
        rigor.invariant('lookup-parity', ({ actual }) => actual !== undefined)
      ])
    ).run({ effort: 1200, seed: 'manager-index-parity' , artifacts: { dir: '', persist: 'never' }});

    const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'lookup-parity');
    assert.ok(inv, 'invariant missing');
    assert.equal(inv.passed, true, `lookup parity violated in ${inv.failureCount} cases`);
  });
});
