import { test } from 'node:test';
import assert from 'node:assert/strict';
import fc from 'fast-check';
import { Arbiter } from '../../src/core/Arbiter.js';
import { PartialGraphContext } from '../../src/core/PartialGraphContext.js';
import { getTrustScore } from '../../src/core/partial-graph/reducers.js';

const LAYERS = [
  'token_projection',
  'workflow_overlay',
  'request_observed',
  'attested_context',
  'challenge_evidence',
  'provenance_overlay',
  'caller_declared'
];

test('fast-check partial context: stacked same-triple facts honor latest reducer within top trust', () => {
  fc.assert(
    fc.property(
      fc.array(
        fc.record({
          ts: fc.integer({ min: 1, max: 1000000 }),
          layer: fc.constantFrom(...LAYERS),
          value: fc.integer({ min: 1, max: 1000000 })
        }),
        { minLength: 2, maxLength: 20 }
      ),
      (inputs) => {
        const arbiter = new Arbiter();
        arbiter.addNode('request:1', 'request');
        arbiter.addNode('time:now', 'timestamp');

        const relations = inputs.map((x) => ({
          src: 'request:1',
          relation: 'request_has_timestamp',
          dst: 'time:now',
          value: x.value,
          updated_last_at: x.ts,
          changed_last_at: x.ts,
          layer_name: x.layer
        }));

        const ctx = new PartialGraphContext(arbiter, {
          options: { reducers: { request_has_timestamp: 'latest' } },
          relations
        });

        const srcId = arbiter.nodeIdByKey.get('request:1');
        const dstId = arbiter.nodeIdByKey.get('time:now');
        const direct = ctx.getDirectRelation(srcId, 'request_has_timestamp', dstId);
        assert.ok(direct);

        const topTrust = Math.max(...inputs.map((x) => getTrustScore(x.layer)));
        const top = inputs.filter((x) => getTrustScore(x.layer) === topTrust);
        const expectedTs = Math.max(...top.map((x) => x.ts));
        assert.equal(direct.updated_last_at, expectedTs);
      }
    ),
    { numRuns: 150 }
  );
});
