/**
 * rigor/config-redefinition.test.js — js-rigor property tests for
 * setRelationConfig redefinition semantics.
 *
 * Redefining a relation's config must take effect immediately: checks
 * served from warm caches must reflect the NEW semantics (the direct-check
 * cache is keyed by the checked relation name and was previously never
 * invalidated by setRelationConfig — a direct r1 -> direct r2 redefinition
 * kept serving the r1 result until TTL expiry).
 *
 * Properties verified:
 *
 *   - REDEFINE PARITY: after every redefinition round, checks equal the
 *     twin arbiter built fresh with the final config (for every config
 *     kind transition, multiple users, and warm caches).
 *   - POST-REDEFINE MUTATIONS: mutations on the new base relations behave
 *     normally after redefinition.
 */
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { rigor } from '@rigor/core';
import { Arbiter } from '../../src/index.js';

const EPS = 1e-9;
const POS = [0, 0.25, 0.5, 0.75, 1];
const USERS = ['user:alice', 'user:bob'];

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;
    }
  };
}

function buildBase() {
  const arb = new Arbiter();
  for (const k of ['user:alice', 'user:bob', 'group:eng', 'doc:1']) {
    arb.addNode(k, k.startsWith('user') ? 'user' : k.startsWith('group') ? 'group' : 'doc');
  }
  arb.setRelationConfig('r1', { type: 'direct' });
  arb.setRelationConfig('r2', { type: 'direct' });
  arb.setRelationConfig('member_of', { type: 'direct' });
  arb.setRelationConfig('viewer', { type: 'direct' });
  return arb;
}

function randomEdges(rng) {
  const edges = [];
  const pairs = [];
  for (const u of USERS) pairs.push([u, 'r1', 'doc:1'], [u, 'r2', 'doc:1']);
  pairs.push(['user:alice', 'member_of', 'group:eng'], ['user:bob', 'member_of', 'group:eng'], ['group:eng', 'viewer', 'doc:1']);
  for (const [src, rel, dst] of pairs) {
    if (rng.next() < 0.6) {
      edges.push([src, rel, dst, POS[Math.floor(rng.next() * POS.length)]]);
    }
  }
  return edges;
}

function applyEdges(arb, edges) {
  for (const [src, rel, dst, p] of edges) arb.addRelation(src, rel, dst, { possibility: p });
}

// Config transition rounds: each round redefines 'can_access' with a new kind
const ROUNDS = [
  { type: 'direct', relation: 'r1' },
  { type: 'direct', relation: 'r2' },
  { type: 'chain', steps: [{ relation: 'member_of', direction: 'out' }, { relation: 'viewer', direction: 'out' }] },
  { union: [{ type: 'direct', relation: 'r1' }, { type: 'direct', relation: 'r2' }] },
  { type: 'defeasible', when: { type: 'direct', relation: 'r1' }, unless: { type: 'direct', relation: 'r2' } },
  { type: 'direct', relation: 'r1' }
];

function checkAll(arb) {
  return USERS.map(u => arb.check(u, 'can_access', 'doc:1', {}).possibility);
}

describe('Config redefinition semantics (rigor)', () => {
  it('REDEFINE PARITY: warm-cache checks match a fresh twin after every redefinition', async () => {
    async function check({ seed }) {
      const rng = mulberry32(seed);
      const edges = randomEdges(rng);
      const arb = buildBase();
      applyEdges(arb, edges);

      // Round 0 config, warm the caches
      arb.setRelationConfig('can_access', ROUNDS[0]);
      checkAll(arb); // warm

      for (let round = 1; round < ROUNDS.length; round++) {
        const config = ROUNDS[round];
        arb.setRelationConfig('can_access', config);

        // Twin: fresh arbiter with the SAME final config and edges
        const twin = buildBase();
        twin.setRelationConfig('can_access', config);
        applyEdges(twin, edges);

        const got = checkAll(arb);
        const expected = checkAll(twin);
        for (let i = 0; i < USERS.length; i++) {
          if (Math.abs(got[i] - expected[i]) > EPS) {
            fail(`round ${round} user ${USERS[i]}: redefined=${got[i]} twin=${expected[i]} edges=${JSON.stringify(edges)}`);
          }
        }

        // Mutate a base relation after redefinition; parity with twin holds
        const rel = ['r1', 'r2'][Math.floor(rng.next() * 2)];
        const user = USERS[Math.floor(rng.next() * 2)];
        const idx = edges.findIndex(e => e[0] === user && e[1] === rel && e[2] === 'doc:1');
        if (idx !== -1) {
          arb.removeRelation(user, rel, 'doc:1');
          twin.removeRelation(user, rel, 'doc:1');
          edges.splice(idx, 1);
        } else {
          const p = POS[Math.floor(rng.next() * POS.length)];
          arb.addRelation(user, rel, 'doc:1', { possibility: p });
          twin.addRelation(user, rel, 'doc:1', { possibility: p });
          edges.push([user, rel, 'doc:1', p]);
        }
        const got2 = checkAll(arb);
        const expected2 = checkAll(twin);
        for (let i = 0; i < USERS.length; i++) {
          if (Math.abs(got2[i] - expected2[i]) > EPS) {
            fail(`round ${round} post-mutation user ${USERS[i]}: redefined=${got2[i]} twin=${expected2[i]}`);
          }
        }
      }
      return { rounds: ROUNDS.length };
    }

    const report = await rigor.campaign(
      [
        rigor.fn('check', check, rigor.args(
          rigor.gen.object({ seed: rigor.gen.int(1, 80000) })
        ))
      ],
      rigor.crucible([
        rigor.invariant('redefine-parity', ({ actual }) => actual !== undefined)
      ])
    ).run({ effort: 1200, seed: 'config-redefinition-parity' , artifacts: { dir: '', persist: 'never' }});

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

  it('BINARY AND FASTPATH follow redefinitions too', async () => {
    async function check({ seed }) {
      const rng = mulberry32(seed);
      const edges = randomEdges(rng);
      const arb = buildBase();
      applyEdges(arb, edges);

      arb.setRelationConfig('can_access', ROUNDS[0]);
      checkAll(arb);

      const config = { type: 'direct', relation: 'r2' };
      arb.setRelationConfig('can_access', config);
      const twin = buildBase();
      twin.setRelationConfig('can_access', config);
      applyEdges(twin, edges);

      for (const u of USERS) {
        const b1 = arb.check(u, 'can_access', 'doc:1', { binary: true, minAllowPossibility: 0.5 });
        const b2 = twin.check(u, 'can_access', 'doc:1', { binary: true, minAllowPossibility: 0.5 });
        if (b1.allow !== b2.allow || Math.abs(b1.possibility - b2.possibility) > EPS) {
          fail(`binary divergence for ${u}: ${JSON.stringify(b1)} vs ${JSON.stringify(b2)}`);
        }
        const f1 = arb.check(u, 'can_access', 'doc:1', { fastPath: true, minAllowPossibility: 0.5 });
        const f2 = twin.check(u, 'can_access', 'doc:1', { fastPath: true, minAllowPossibility: 0.5 });
        if (Math.abs(f1.possibility - f2.possibility) > EPS) {
          fail(`fastPath divergence for ${u}: ${f1.possibility} vs ${f2.possibility}`);
        }
      }
      return { users: USERS.length };
    }

    const report = await rigor.campaign(
      [
        rigor.fn('check', check, rigor.args(
          rigor.gen.object({ seed: rigor.gen.int(1, 80000) })
        ))
      ],
      rigor.crucible([
        rigor.invariant('redefine-binary-fastpath', ({ actual }) => actual !== undefined)
      ])
    ).run({ effort: 800, seed: 'config-redefinition-binary' , artifacts: { dir: '', persist: 'never' }});

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