import { afterEach, describe, expect, it, vi } from 'vitest';

import {
  canReuseInitialSearchArtifacts,
  normalizeSearchPlanRoundFailureReason,
  resolveFixedRuntimeCandidateLimit,
  resolveFixedRuntimePageCount,
} from './row-pipeline.ts';

afterEach(() => {
  vi.unstubAllEnvs();
});

describe('row-pipeline initial search recovery', () => {
  it('normalizes known round failure reasons', () => {
    expect(normalizeSearchPlanRoundFailureReason('captcha_intercept')).toBe('captcha_intercept');
    expect(normalizeSearchPlanRoundFailureReason('search_service_error')).toBe('search_service_error');
    expect(normalizeSearchPlanRoundFailureReason('unexpected')).toBe('');
  });

  it('reuses artifacts when captcha interception is the only output', () => {
    expect(canReuseInitialSearchArtifacts({
      validRound: null,
      initialRounds: [{ round_failure_reason: 'captcha_intercept' }],
    })).toBe(true);
  });

  it('reuses artifacts when results were already generated', () => {
    expect(canReuseInitialSearchArtifacts({
      validRound: null,
      initialRounds: [{ results_path: '/tmp/run/results.json' }],
    })).toBe(true);
  });

  it('does not reuse empty generic failures', () => {
    expect(canReuseInitialSearchArtifacts({
      validRound: null,
      initialRounds: [{ round_failure_reason: 'round_failed' }],
    })).toBe(false);
  });
});

describe('fixed runtime page count config', () => {
  it('defaults to 2 pages when the env value is missing or invalid', () => {
    vi.stubEnv('SEARCH_FIXED_RUNTIME_PAGE_COUNT', '');
    expect(resolveFixedRuntimePageCount()).toBe(2);
    expect(resolveFixedRuntimePageCount(null)).toBe(2);
    expect(resolveFixedRuntimePageCount('')).toBe(2);
    expect(resolveFixedRuntimePageCount('0')).toBe(2);
    expect(resolveFixedRuntimePageCount('abc')).toBe(2);
    expect(resolveFixedRuntimePageCount('1abc')).toBe(2);
  });

  it('uses the configured page count to compute the candidate limit', () => {
    vi.stubEnv('SEARCH_FIXED_RUNTIME_PAGE_COUNT', '1');
    expect(resolveFixedRuntimePageCount()).toBe(1);
    expect(resolveFixedRuntimePageCount('1')).toBe(1);
    expect(resolveFixedRuntimeCandidateLimit(1)).toBe(60);
    expect(resolveFixedRuntimeCandidateLimit(3)).toBe(180);
  });

  it('caps the configured page count at 3 pages', () => {
    vi.stubEnv('SEARCH_FIXED_RUNTIME_PAGE_COUNT', '4');
    expect(resolveFixedRuntimePageCount()).toBe(3);
    expect(resolveFixedRuntimePageCount('4')).toBe(3);
    expect(resolveFixedRuntimePageCount('12')).toBe(3);
    expect(resolveFixedRuntimeCandidateLimit(resolveFixedRuntimePageCount('12'))).toBe(180);
  });
});
