/**
 * Tests for handleAIServiceFailure's error categorisation + broadcast policy.
 *
 * Behavioural contract:
 *   • PERSISTENT failures (auth, unknown) → broadcast `agent_error`
 *     so the UI banner / Telegram fanout reach the user.
 *   • TRANSIENT failures (rate-limit, provider-overload, gateway, network)
 *     → silent. They self-heal; broadcasting them every retry cycle was
 *     the source of the Telegram floods.
 *   • Token-limit → handled by the compaction path (early return),
 *     never broadcasts directly from this function.
 *
 * The classification regexes are the most likely source of regression —
 * cover the named status codes (401/403/429/503/504/529) plus the common
 * textual variants we saw in production logs.
 */

import { jest, describe, test, expect, beforeEach } from '@jest/globals';
import { createMockLogger } from '../../__test-utils__/mockFactories.js';

const mockShouldAgentBeActive = jest.fn(() => ({ active: false, reason: 'idle' }));
const mockGetActiveAgents = jest.fn(() => []);
const mockShouldSkipIteration = jest.fn(() => false);
jest.unstable_mockModule('../../services/agentActivityService.js', () => ({
  shouldAgentBeActive: mockShouldAgentBeActive,
  getActiveAgents: mockGetActiveAgents,
  shouldSkipIteration: mockShouldSkipIteration,
}));

const { default: AgentScheduler } = await import('../agentScheduler.js');

function makeScheduler() {
  const logger = createMockLogger();
  const agent = { id: 'a1', name: 'TestAgent', sessionId: 'sess-1' };
  const agentPool = {
    getAgent: jest.fn().mockResolvedValue(agent),
    persistAgentState: jest.fn().mockResolvedValue(undefined),
    addToolResult: jest.fn().mockResolvedValue(undefined),
  };
  const broadcasts = [];
  const webSocketManager = {
    broadcastToSession: jest.fn((sessionId, payload) => broadcasts.push({ sessionId, payload })),
  };
  const aiService = { abortRequest: jest.fn(), getActiveRequest: () => null };
  const scheduler = new AgentScheduler(agentPool, {}, aiService, logger);
  scheduler.webSocketManager = webSocketManager;
  scheduler.broadcastAgentStateUpdate = jest.fn().mockResolvedValue(undefined);
  scheduler.getAgentSession = jest.fn(() => 'sess-1');
  return { scheduler, agentPool, broadcasts, agent };
}

const errorClasses = [
  // -- TRANSIENT (no broadcast) --
  { name: 'rate-limit text',         msg: 'Rate limit exceeded', expectBroadcast: false, label: 'rate-limit' },
  { name: 'rate-limit 429',          msg: 'HTTP 429 Too Many Requests', expectBroadcast: false, label: 'rate-limit' },
  { name: 'provider overload 529',   msg: 'HTTP 529 Overloaded',  expectBroadcast: false, label: 'provider-overload' },
  { name: 'provider overload text',  msg: 'The model is overloaded with requests', expectBroadcast: false, label: 'provider-overload' },
  { name: 'server is busy',          msg: 'Sorry, the server is busy. Please try again.', expectBroadcast: false, label: 'provider-overload' },
  { name: 'capacity error',          msg: 'Provider returned a capacity error', expectBroadcast: false, label: 'provider-overload' },
  { name: 'gateway 503',             msg: 'HTTP 503 Service Unavailable', expectBroadcast: false, label: 'gateway-error' },
  { name: 'gateway 504',             msg: '504 Gateway Timeout from upstream', expectBroadcast: false, label: 'gateway-error' },
  { name: 'bad gateway',             msg: 'Got a bad gateway response', expectBroadcast: false, label: 'gateway-error' },
  { name: 'upstream',                msg: 'Upstream connect error', expectBroadcast: false, label: 'gateway-error' },
  { name: 'network ECONNREFUSED',    msg: 'ECONNREFUSED 127.0.0.1', expectBroadcast: false, label: 'network-error' },
  { name: 'network ETIMEDOUT',       msg: 'connect ETIMEDOUT', expectBroadcast: false, label: 'network-error' },
  { name: 'network ENOTFOUND',       msg: 'getaddrinfo ENOTFOUND api.foo', expectBroadcast: false, label: 'network-error' },
  { name: 'fetch failed',            msg: 'fetch failed', expectBroadcast: false, label: 'network-error' },
  // -- PERSISTENT (broadcast) --
  { name: 'auth: API key',           msg: 'Invalid API key provided',           expectBroadcast: true, label: 'api-key-error' },
  { name: 'auth: 401',               msg: 'HTTP 401 Unauthorized',              expectBroadcast: true, label: 'api-key-error' },
  { name: 'auth: 403',               msg: 'HTTP 403 Forbidden',                  expectBroadcast: true, label: 'api-key-error' },
  { name: 'unknown: random 500',     msg: 'Random 500 Internal Server Error from the AI', expectBroadcast: true, label: 'server-error' },
  { name: 'unknown: weird shape',    msg: 'Provider returned malformed JSON',   expectBroadcast: true, label: 'server-error' },
];

describe('handleAIServiceFailure: error categorisation', () => {
  describe.each(errorClasses)('%s', (tc) => {
    let scheduler, broadcasts;
    beforeEach(() => {
      jest.clearAllMocks();
      ({ scheduler, broadcasts } = makeScheduler());
    });

    test(`"${tc.msg}" → broadcast=${tc.expectBroadcast}, state="${tc.label}"`, async () => {
      await scheduler.handleAIServiceFailure('a1', new Error(tc.msg));

      const agentErrorBroadcasts = broadcasts.filter(b => b.payload?.type === 'agent_error');
      if (tc.expectBroadcast) {
        expect(agentErrorBroadcasts.length).toBe(1);
        expect(agentErrorBroadcasts[0].payload.data.error).toBe(tc.msg);
      } else {
        expect(agentErrorBroadcasts.length).toBe(0);
      }
      // Every branch must publish an agent-state hint so the UI shows the
      // right pause reason; verify the label we expect.
      expect(scheduler.broadcastAgentStateUpdate).toHaveBeenCalledWith('a1', tc.label);
    });
  });
});

describe('handleAIServiceFailure: gateway 503 takes the network delay, not the rate-limit delay', () => {
  test('uses NETWORK_ERROR_DELAY_MS for 503 errors', async () => {
    const { scheduler, agentPool, agent } = makeScheduler();
    const beforeMs = Date.now();
    await scheduler.handleAIServiceFailure('a1', new Error('HTTP 503 Service Unavailable'));

    // delayEndTime is in agent.delayEndTime as ISO; should be ~30s out.
    const elapsedMs = new Date(agent.delayEndTime).getTime() - beforeMs;
    // Use a generous range to tolerate test-machine drift.
    expect(elapsedMs).toBeGreaterThanOrEqual(20 * 1000);
    expect(elapsedMs).toBeLessThanOrEqual(90 * 1000);
    expect(agentPool.persistAgentState).toHaveBeenCalledWith('a1');
  });
});

describe('handleAIServiceFailure: token-limit path early-returns without broadcasting', () => {
  test('does not call broadcastToSession for token-limit errors', async () => {
    const { scheduler, broadcasts } = makeScheduler();
    // Stub the token-limit handler so we don't fall into its compaction logic.
    scheduler.handleTokenLimitError = jest.fn().mockResolvedValue(undefined);
    scheduler.isTokenLimitError = jest.fn().mockReturnValue(true);

    await scheduler.handleAIServiceFailure('a1', new Error('Context length exceeded'));

    expect(scheduler.handleTokenLimitError).toHaveBeenCalledWith('a1', expect.any(Object), expect.any(Error));
    // Importantly: no agent_error broadcast from this path.
    expect(broadcasts.filter(b => b.payload?.type === 'agent_error').length).toBe(0);
  });
});

describe('isTokenLimitError: regex-free implementation preserves all original patterns', () => {
  // The original implementation matched these literal substrings plus a
  // `/maximum.*exceeded/` regex. The refactored version replaces the
  // regex with a two-indexOf check. Cover both halves explicitly.
  const positives = [
    'prompt is too long for this model',
    'too many tokens for the model',
    'context length exceeded the limit',
    'context window exceeded',
    'maximum context size reached',
    'token limit reached for this request',
    'max_tokens is set too high',
    'context_length_exceeded: request had 200000 tokens',
    // The 'maximum.*exceeded' case — "maximum" appears before "exceeded".
    'maximum response limit exceeded for input',
    'maximum 100k context length exceeded by 5k tokens',
  ];
  const negatives = [
    'rate limit exceeded',
    'connection timed out',
    'maximum retries reached',         // has "maximum" but no "exceeded" after it
    'something exceeded the maximum',  // "exceeded" appears BEFORE "maximum" — old regex required maximum→exceeded order
    'random unrelated error',
  ];

  describe.each(positives)('positive: %s', (msg) => {
    test('classifies as token-limit', () => {
      const { scheduler } = makeScheduler();
      expect(scheduler.isTokenLimitError(msg.toLowerCase())).toBe(true);
    });
  });

  describe.each(negatives)('negative: %s', (msg) => {
    test('does not classify as token-limit', () => {
      const { scheduler } = makeScheduler();
      expect(scheduler.isTokenLimitError(msg.toLowerCase())).toBe(false);
    });
  });
});
