/**
 * rigor/logical-operators.test.js — js-rigor property tests for LogicalOperators.
 *
 * LogicalOperators handles union, intersection, exclusion, and defeasible logic
 * combinations via OWA fusion. Properties verified using a mock ruleEvaluator:
 *
 *   - union with aggregator='max' → result.possibility = max(child possibilities)
 *   - union with aggregator='mean' → result.possibility ≈ average of children
 *   - intersection with aggregator='min' → result.possibility = min(children)
 *   - exclusion (A AND NOT B) → high when A high, B low; low when A low, B high
 *   - collectedValues are passed through from child rules
 *   - meta.operation indicates which logical operation was applied
 *   - result.possibility ∈ [0, 1]
 */
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { rigor } from '@rigor/core';
import { LogicalOperators } from '../../src/authorization/rules/LogicalOperators.js';

/**
 * Build a mock ruleEvaluator that returns a fixed possibility for each rule.
 * Each rule is identified by mockKey; the evaluator looks up by mockKey.
 */
function makeMockRuleEvaluator(resultsByMockKey) {
  return {
    evaluateRule(userId, userKey, objectId, objectKey, rule) {
      if (rule && rule.mockKey) {
        return resultsByMockKey[rule.mockKey] ||
          { possibility: 0, reliability: 1.0, meta: { ruleType: 'direct' }, collectedValues: [] };
      }
      return { possibility: 0, reliability: 1.0, meta: { ruleType: 'direct' }, collectedValues: [] };
    }
  };
}

describe('LogicalOperators evaluation (rigor)', () => {
  it('union with aggregator=max → possibility = max(child possibilities)', async () => {
    async function check(possA, possB, possC) {
      const evaluator = makeMockRuleEvaluator({
        a: { possibility: possA, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'a' } }, collectedValues: [1] },
        b: { possibility: possB, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'b' } }, collectedValues: [2] },
        c: { possibility: possC, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'c' } }, collectedValues: [3] }
      });
      const logicalOps = new LogicalOperators({}, evaluator);
      const rule = { type: 'logical', union: { rules: [{ mockKey: 'a' }, { mockKey: 'b' }, { mockKey: 'c' }], aggregator: 'max' } };
      const result = logicalOps._evaluateRule('u', 'u', 'o', 'o', rule, new Set(), null, { collectValues: true });
      const expected = Math.max(possA, possB, possC);
      if (Math.abs(result.possibility - expected) > 0.001) {
        throw new Error(`max aggregator: expected ${expected}, got ${result.possibility}`);
      }
      if (result.meta?.operation !== 'union') {
        throw new Error(`meta.operation=${result.meta?.operation}, expected 'union'`);
      }
      return result;
    }

    const report = await rigor.campaign(
      [rigor.fn('check', check,
        rigor.args(
          rigor.gen.float({ min: 0, max: 1 }),
          rigor.gen.float({ min: 0, max: 1 }),
          rigor.gen.float({ min: 0, max: 1 })
        )
      )],
      rigor.crucible([
        rigor.invariant('union-max', ({ actual }) => actual !== undefined)
      ])
    ).run({ seed: 'logical-operators-union-max', effort: 1500 , artifacts: { dir: '', persist: 'never' }});

    if (process.env.TEST_DEBUG === '1') console.log(report.toTAP());
    const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'union-max');
    assert.ok(inv);
    assert.equal(inv.passed, true, `union-max contract violated in ${inv.failureCount} cases`);
  });

  it('intersection with aggregator=min → possibility = min(child possibilities)', async () => {
    async function check(possA, possB, possC) {
      const evaluator = makeMockRuleEvaluator({
        a: { possibility: possA, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'a' } }, collectedValues: [1] },
        b: { possibility: possB, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'b' } }, collectedValues: [2] },
        c: { possibility: possC, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'c' } }, collectedValues: [3] }
      });
      const logicalOps = new LogicalOperators({}, evaluator);
      const rule = { type: 'logical', intersection: { rules: [{ mockKey: 'a' }, { mockKey: 'b' }, { mockKey: 'c' }], aggregator: 'min' } };
      const result = logicalOps._evaluateRule('u', 'u', 'o', 'o', rule, new Set(), null, { collectValues: true });
      const expected = Math.min(possA, possB, possC);
      if (Math.abs(result.possibility - expected) > 0.001) {
        throw new Error(`min aggregator: expected ${expected}, got ${result.possibility}`);
      }
      if (result.meta?.operation !== 'intersection') {
        throw new Error(`meta.operation=${result.meta?.operation}, expected 'intersection'`);
      }
      return result;
    }

    const report = await rigor.campaign(
      [rigor.fn('check', check,
        rigor.args(
          rigor.gen.float({ min: 0, max: 1 }),
          rigor.gen.float({ min: 0, max: 1 }),
          rigor.gen.float({ min: 0, max: 1 })
        )
      )],
      rigor.crucible([
        rigor.invariant('intersection-min', ({ actual }) => actual !== undefined)
      ])
    ).run({ seed: 'logical-operators-intersection-min', effort: 1500 , artifacts: { dir: '', persist: 'never' }});

    if (process.env.TEST_DEBUG === '1') console.log(report.toTAP());
    const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'intersection-min');
    assert.ok(inv);
    assert.equal(inv.passed, true, `intersection-min contract violated in ${inv.failureCount} cases`);
  });

  it('union with aggregator=mean → possibility ≈ average of children', async () => {
    async function check(possA, possB) {
      const evaluator = makeMockRuleEvaluator({
        a: { possibility: possA, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'a' } }, collectedValues: [1] },
        b: { possibility: possB, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'b' } }, collectedValues: [2] }
      });
      const logicalOps = new LogicalOperators({}, evaluator);
      const rule = { type: 'logical', union: { rules: [{ mockKey: 'a' }, { mockKey: 'b' }], aggregator: 'mean' } };
      const result = logicalOps._evaluateRule('u', 'u', 'o', 'o', rule, new Set(), null, { collectValues: true });
      const expected = (possA + possB) / 2;
      if (Math.abs(result.possibility - expected) > 0.001) {
        throw new Error(`mean aggregator: expected ${expected}, got ${result.possibility}`);
      }
      return result;
    }

    const report = await rigor.campaign(
      [rigor.fn('check', check,
        rigor.args(
          rigor.gen.float({ min: 0, max: 1 }),
          rigor.gen.float({ min: 0, max: 1 })
        )
      )],
      rigor.crucible([
        rigor.invariant('union-mean', ({ actual }) => actual !== undefined)
      ])
    ).run({ seed: 'logical-operators-union-mean', effort: 1500 , artifacts: { dir: '', persist: 'never' }});

    if (process.env.TEST_DEBUG === '1') console.log(report.toTAP());
    const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'union-mean');
    assert.ok(inv);
    assert.equal(inv.passed, true, `union-mean contract violated in ${inv.failureCount} cases`);
  });

  it('exclusion (A AND NOT B) → high when A high, B low', async () => {
    async function check(possA, possB) {
      const evaluator = makeMockRuleEvaluator({
        a: { possibility: possA, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'a' } }, collectedValues: [1] },
        b: { possibility: possB, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'b' } }, collectedValues: [2] }
      });
      const logicalOps = new LogicalOperators({}, evaluator);
      // exclusion is its own field, not an intersection aggregator
      const rule = { type: 'logical', exclusion: { rules: [{ mockKey: 'a' }, { mockKey: 'b' }] } };
      const result = logicalOps._evaluateRule('u', 'u', 'o', 'o', rule, new Set(), null, { collectValues: true });
      // A AND NOT B is high when A high, B low
      if (possA > 0.8 && possB < 0.2) {
        if (result.possibility < 0.5) {
          throw new Error(`A high, B low: expected high exclusion, got ${result.possibility}`);
        }
      }
      // A AND NOT B is low when A low, B high
      if (possA < 0.2 && possB > 0.8) {
        if (result.possibility > 0.5) {
          throw new Error(`A low, B high: expected low exclusion, got ${result.possibility}`);
        }
      }
      return result;
    }

    const report = await rigor.campaign(
      [rigor.fn('check', check,
        rigor.args(
          rigor.gen.float({ min: 0, max: 1 }),
          rigor.gen.float({ min: 0, max: 1 })
        )
      )],
      rigor.crucible([
        rigor.invariant('exclusion', ({ actual }) => actual !== undefined)
      ])
    ).run({ seed: 'logical-operators-exclusion', effort: 1500 , artifacts: { dir: '', persist: 'never' }});

    if (process.env.TEST_DEBUG === '1') console.log(report.toTAP());
    const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'exclusion');
    assert.ok(inv);
    assert.equal(inv.passed, true, `exclusion contract violated in ${inv.failureCount} cases`);
  });

  it('result.possibility ∈ [0, 1] always (union, intersection, exclusion)', async () => {
    async function check(possA, possB) {
      const evaluator = makeMockRuleEvaluator({
        a: { possibility: possA, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'a' } }, collectedValues: [1] },
        b: { possibility: possB, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'b' } }, collectedValues: [2] }
      });
      const logicalOps = new LogicalOperators({}, evaluator);
      const rule = { type: 'logical', union: { rules: [{ mockKey: 'a' }, { mockKey: 'b' }], aggregator: 'max' } };
      const result = logicalOps._evaluateRule('u', 'u', 'o', 'o', rule, new Set(), null, { collectValues: true });
      if (result.possibility < 0 || result.possibility > 1) {
        throw new Error(`possibility=${result.possibility} outside [0,1]`);
      }
      return result;
    }

    const report = await rigor.campaign(
      [rigor.fn('check', check,
        rigor.args(
          rigor.gen.float({ min: 0, max: 1 }),
          rigor.gen.float({ min: 0, max: 1 })
        )
      )],
      rigor.crucible([
        rigor.invariant('possibility-bounded', ({ actual }) => actual !== undefined)
      ])
    ).run({ seed: 'logical-operators-possibility-bounded', effort: 1500 , artifacts: { dir: '', persist: 'never' }});

    if (process.env.TEST_DEBUG === '1') console.log(report.toTAP());
    const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'possibility-bounded');
    assert.ok(inv);
    assert.equal(inv.passed, true, `possibility-bounded violated in ${inv.failureCount} cases`);
  });

  it('collectedValues from child rules are concatenated', async () => {
    async function check(possA, possB) {
      const evaluator = makeMockRuleEvaluator({
        a: { possibility: possA, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'a' } }, collectedValues: ['val-a'] },
        b: { possibility: possB, reliability: 1.0, meta: { ruleType: 'direct', rule: { mockKey: 'b' } }, collectedValues: ['val-b'] }
      });
      const logicalOps = new LogicalOperators({}, evaluator);
      const rule = { type: 'logical', union: { rules: [{ mockKey: 'a' }, { mockKey: 'b' }], aggregator: 'max' } };
      const result = logicalOps._evaluateRule('u', 'u', 'o', 'o', rule, new Set(), null, { collectValues: true });
      if (!Array.isArray(result.collectedValues)) {
        throw new Error(`collectedValues not an array: ${JSON.stringify(result.collectedValues)}`);
      }
      // Both should be present
      if (!result.collectedValues.includes('val-a') || !result.collectedValues.includes('val-b')) {
        throw new Error(`collectedValues missing child values: ${JSON.stringify(result.collectedValues)}`);
      }
      return result;
    }

    const report = await rigor.campaign(
      [rigor.fn('check', check,
        rigor.args(
          rigor.gen.float({ min: 0.5, max: 1 }),
          rigor.gen.float({ min: 0.5, max: 1 })
        )
      )],
      rigor.crucible([
        rigor.invariant('collected-values-concat', ({ actual }) => actual !== undefined)
      ])
    ).run({ seed: 'logical-operators-collected-values', effort: 800 , artifacts: { dir: '', persist: 'never' }});

    if (process.env.TEST_DEBUG === '1') console.log(report.toTAP());
    const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'collected-values-concat');
    assert.ok(inv);
    assert.equal(inv.passed, true, `collected-values-concat violated in ${inv.failureCount} cases`);
  });
});
