/**
 * SET 101c — after L2 pass 1 no-improvement with unchanged finding hash,
 * skip passes 2/3 and escalate (emit short-circuit line).
 */
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';

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: L2 redraws the incumbent (no improvement, finding hash unchanged). */
class NoImproveLlm {
  l2Calls = 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(_input: unknown, o?: { purpose?: string }) {
    if (/^L2 procedure:/.test(o?.purpose ?? '')) this.l2Calls++;
    return [{ path: 'src/adder.ts', content: WRONG }];
  }
}

describe('SET 101c — L2 short-circuit', () => {
  it('after pass 1 no-improvement + unchanged finding hash, skips passes 2/3', async () => {
    const llm = new NoImproveLlm();
    const res = await runTier1Job({
      prompt: 'adder',
      llm: llm as unknown as LlmClient,
      runSuite: makeEvalSuiteRunner(),
      gates: { maxPasses: 6, stallLimit: 5, progressStall: 5 },
    });

    expect(res.log.some(e =>
      /L2 short-circuit: world unchanged — escalating/.test(e.message),
    )).toBe(true);
    expect(res.metrics.l2ShortCircuits).toBeGreaterThanOrEqual(1);
    // Only pass 1 fires as an L2 procedure draw for the focus class.
    expect(llm.l2Calls).toBe(1);
    expect(res.metrics.l2Draws).toBe(1);
    expect(res.log.filter(e => /^L2 procedure loop [23]\//.test(e.message))).toHaveLength(0);
  });
});
