/**
 * SET 101b — observatory poll batch skipped when world has not advanced
 * since the last poll (same predicate as watcher synthesis skip).
 */
import { describe, expect, it } from 'vitest';
import type { FeatureSpec, LlmClient } from '../src/core/types';
import { runTier1Job } from '../src/tier1/runner';
import { makeEvalSuiteRunner } from '../src/tier1/testExec';
import { OBSERVATION_POLLS } from '../src/tier1/observatory';

const WRONG = 'export function add(a: number, b: number): number { return a - b; }';

function makeSpec(): FeatureSpec {
  return {
    title: 'Adder', prompt: 'adder',
    features: [{
      id: 'F1', name: 'add', description: 'adds two numbers', parentId: null,
      deps: [], files: ['src/adder.ts'], testFile: 'tests/f1-add.test.ts',
      edgeCases: ['zero'], envVars: [],
      exports: [{ file: 'src/adder.ts', symbol: 'add' }],
      stubs: [{
        path: 'src/adder.ts',
        content: "export function add(a: number, b: number): number { throw new Error('stub'); }",
      }],
    }],
  } as unknown as FeatureSpec;
}

/** Class double: never heals — two+ repair cycles with identical world. */
class StaleWorldObservatoryLlm {
  observeCalls = 0;

  async encodeFeatures() { return makeSpec(); }
  async generateTests() { return { content: '', parts: { imports: [], cases: [] } }; }
  async fixTestCases(_s: unknown, _f: unknown, req: { name: string }[]) {
    const name = req[0]!.name;
    return {
      cases: [{
        name,
        kind: (name === 'zero' ? 'edge' : 'behavior') as 'edge' | 'behavior',
        body: name === 'zero' ? 'expect(add(7, 0)).toBe(7);' : 'expect(add(2, 3)).toBe(5);',
      }],
    };
  }
  async generateImplementation() {
    return [{ path: 'src/adder.ts', content: WRONG }];
  }
  async repair() {
    return [{ path: 'src/adder.ts', content: WRONG }];
  }
  async observe() {
    this.observeCalls++;
    return 'ITEM: add — subtracts where the contract requires a sum';
  }
}

describe('SET 101b — observatory poll gate', () => {
  it('skips poll batch 2 when world is unchanged; emits one skip line', async () => {
    const llm = new StaleWorldObservatoryLlm();
    const res = await runTier1Job({
      prompt: 'adder',
      llm: llm as unknown as LlmClient,
      runSuite: makeEvalSuiteRunner(),
      gates: { maxPasses: 6, stallLimit: 5, progressStall: 5 },
    });

    expect(res.metrics.observatoryPollsSkipped).toBeGreaterThanOrEqual(1);
    expect(res.log.some(e =>
      /observatory: polls skipped — world unchanged since node \d+/.test(e.message),
    )).toBe(true);
    // First batch still polls; later batches with unchanged world do not.
    expect(llm.observeCalls).toBeLessThanOrEqual(OBSERVATION_POLLS.length);
    expect(res.metrics.observationPolls).toBe(llm.observeCalls);
  });
});
