/**
 * Integration Tests: All 59 MCP Tools Coverage
 * 
 * Validates that every registered MCP tool:
 * 1. Returns valid MCP-compliant response structure
 * 2. Returns real data derived from EP API (no mock/hardcoded data)
 * 3. Handles errors gracefully
 * 
 * ISMS Policy: SC-002 (Secure Testing), PE-001 (Performance Testing)
 * Compliance: ISO 27001 (AU-2), NIST CSF 2.0 (DE.CM-6), CIS Controls v8.1 (8.11)
 * 
 * @see https://data.europarl.europa.eu/api/v2/
 */

import { describe, it, expect, beforeEach } from 'vitest';
import { shouldRunIntegrationTests } from '../setup.js';
import { retryOrSkip } from '../../helpers/testUtils.js';
import { validateMCPStructure } from '../helpers/responseValidator.js';

// ── Core Tools ──────────────────────────────────────────────────
import { handleGetMEPs } from '../../../src/tools/getMEPs.js';
import { handleGetMEPDetails } from '../../../src/tools/getMEPDetails.js';
import { handleGetPlenarySessions } from '../../../src/tools/getPlenarySessions.js';
import { handleGetVotingRecords } from '../../../src/tools/getVotingRecords.js';
import { handleSearchDocuments } from '../../../src/tools/searchDocuments.js';
import { handleGetCommitteeInfo } from '../../../src/tools/getCommitteeInfo.js';
import { handleGetParliamentaryQuestions } from '../../../src/tools/getParliamentaryQuestions.js';

// ── Advanced Analysis Tools ─────────────────────────────────────
import { handleAnalyzeVotingPatterns } from '../../../src/tools/analyzeVotingPatterns.js';
import { handleTrackLegislation } from '../../../src/tools/trackLegislation/index.js';
import { handleGenerateReport } from '../../../src/tools/generateReport/index.js';

// ── Phase 1 OSINT Intelligence Tools ────────────────────────────
import { handleAssessMepInfluence } from '../../../src/tools/assessMepInfluence.js';
import { handleAnalyzeCoalitionDynamics } from '../../../src/tools/analyzeCoalitionDynamics.js';
import { handleDetectVotingAnomalies } from '../../../src/tools/detectVotingAnomalies.js';
import { handleComparePoliticalGroups } from '../../../src/tools/comparePoliticalGroups.js';
import { handleAnalyzeLegislativeEffectiveness } from '../../../src/tools/analyzeLegislativeEffectiveness.js';
import { handleMonitorLegislativePipeline } from '../../../src/tools/monitorLegislativePipeline.js';

// ── Phase 2 OSINT Intelligence Tools ────────────────────────────
import { handleAnalyzeCommitteeActivity } from '../../../src/tools/analyzeCommitteeActivity.js';
import { handleTrackMepAttendance } from '../../../src/tools/trackMepAttendance.js';

// ── Phase 3 OSINT Intelligence Tools ────────────────────────────
import { handleAnalyzeCountryDelegation } from '../../../src/tools/analyzeCountryDelegation.js';
import { handleGeneratePoliticalLandscape } from '../../../src/tools/generatePoliticalLandscape.js';

// ── Phase 4 EP API v2 Tools ─────────────────────────────────────
import { handleGetCurrentMEPs } from '../../../src/tools/getCurrentMEPs.js';
import { handleGetSpeeches } from '../../../src/tools/getSpeeches.js';
import { handleGetProcedures } from '../../../src/tools/getProcedures.js';
import { handleGetAdoptedTexts } from '../../../src/tools/getAdoptedTexts.js';
import { handleGetEvents } from '../../../src/tools/getEvents.js';
import { handleGetMeetingActivities } from '../../../src/tools/getMeetingActivities.js';
import { handleGetMeetingDecisions } from '../../../src/tools/getMeetingDecisions.js';
import { handleGetMEPDeclarations } from '../../../src/tools/getMEPDeclarations.js';

// ── Phase 6 Advanced OSINT Tools ────────────────────────────────
import { handleNetworkAnalysis } from '../../../src/tools/networkAnalysis.js';
import { handleSentimentTracker } from '../../../src/tools/sentimentTracker.js';
import { handleEarlyWarningSystem } from '../../../src/tools/earlyWarningSystem.js';
import { handleComparativeIntelligence } from '../../../src/tools/comparativeIntelligence.js';
import { handleCorrelateIntelligence } from '../../../src/tools/correlateIntelligence.js';

// ── Phase 5 EP API v2 Tools ─────────────────────────────────────
import { handleGetIncomingMEPs } from '../../../src/tools/getIncomingMEPs.js';
import { handleGetOutgoingMEPs } from '../../../src/tools/getOutgoingMEPs.js';
import { handleGetHomonymMEPs } from '../../../src/tools/getHomonymMEPs.js';
import { handleGetPlenaryDocuments } from '../../../src/tools/getPlenaryDocuments.js';
import { handleGetCommitteeDocuments } from '../../../src/tools/getCommitteeDocuments.js';
import { handleGetPlenarySessionDocuments } from '../../../src/tools/getPlenarySessionDocuments.js';
import { handleGetPlenarySessionDocumentItems } from '../../../src/tools/getPlenarySessionDocumentItems.js';
import { handleGetControlledVocabularies } from '../../../src/tools/getControlledVocabularies.js';
import { handleGetExternalDocuments } from '../../../src/tools/getExternalDocuments.js';
import { handleGetMeetingForeseenActivities } from '../../../src/tools/getMeetingForeseenActivities.js';
import { handleGetProcedureEvents } from '../../../src/tools/getProcedureEvents.js';
import { handleGetMeetingPlenarySessionDocuments } from '../../../src/tools/getMeetingPlenarySessionDocuments.js';
import { handleGetMeetingPlenarySessionDocumentItems } from '../../../src/tools/getMeetingPlenarySessionDocumentItems.js';

// ── Feed Endpoint Tools ─────────────────────────────────────────
import { handleGetMEPsFeed } from '../../../src/tools/getMEPsFeed.js';
import { handleGetEventsFeed } from '../../../src/tools/getEventsFeed.js';
import { handleGetProceduresFeed } from '../../../src/tools/getProceduresFeed.js';
import { handleGetAdoptedTextsFeed } from '../../../src/tools/getAdoptedTextsFeed.js';
import { handleGetMEPDeclarationsFeed } from '../../../src/tools/getMEPDeclarationsFeed.js';
import { handleGetDocumentsFeed } from '../../../src/tools/getDocumentsFeed.js';
import { handleGetPlenaryDocumentsFeed } from '../../../src/tools/getPlenaryDocumentsFeed.js';
import { handleGetCommitteeDocumentsFeed } from '../../../src/tools/getCommitteeDocumentsFeed.js';
import { handleGetPlenarySessionDocumentsFeed } from '../../../src/tools/getPlenarySessionDocumentsFeed.js';
import { handleGetExternalDocumentsFeed } from '../../../src/tools/getExternalDocumentsFeed.js';
import { handleGetParliamentaryQuestionsFeed } from '../../../src/tools/getParliamentaryQuestionsFeed.js';
import { handleGetCorporateBodiesFeed } from '../../../src/tools/getCorporateBodiesFeed.js';
import { handleGetControlledVocabulariesFeed } from '../../../src/tools/getControlledVocabulariesFeed.js';

const describeIntegration = shouldRunIntegrationTests() ? describe : describe.skip;

/**
 * Helper: parse response JSON and validate it contains no mock markers
 */
function parseAndValidateNoMockData(result: { content: { type: string; text: string }[] }): unknown {
  validateMCPStructure(result);
  const text = result.content[0]?.text ?? '{}';
  const parsed: unknown = JSON.parse(text);
  
  // Ensure no NONE confidence level (indicates mock data)
  const textLower = text.toLowerCase();
  expect(textLower).not.toContain('"confidencelevel":"none"');
  expect(textLower).not.toContain('"confidencelevel": "none"');
  expect(text).not.toContain('PLACEHOLDER DATA');
  expect(text).not.toContain('createMockProcedure');
  
  return parsed;
}

/**
 * Extracts numeric MEP IDs from EP API string IDs (format: "person/124936").
 * Returns up to `count` numeric IDs from the `testMEPIds` array.
 */
function resolveNumericMepIds(firstId: string, count: number, allIds: string[] = []): number[] {
  const ids = allIds.length > 0 ? allIds : (firstId ? [firstId] : []);
  return ids
    .map(id => {
      const numStr = id.includes('/') ? id.split('/').pop() ?? '' : id;
      return parseInt(numStr, 10);
    })
    .filter(id => !isNaN(id) && id > 0)
    .slice(0, count);
}

describeIntegration('All 59 MCP Tools Integration Coverage', () => {
  // Shared MEP ID resolved once for tests that need it
  let testMEPId: string;
  let testMEPIds: string[] = [];
  let testSessionId: string;
  let testProcedureId: string;

  beforeEach(async () => {
    // Rate limit respect
    await new Promise(resolve => setTimeout(resolve, 2000));
  });

  // ══════════════════════════════════════════════════════════════
  // CORE TOOLS (7)
  // ══════════════════════════════════════════════════════════════

  describe('Core Tool: get_meps', () => {
    it('should return real MEP data from EP API', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetMEPs({ limit: 5 }),
        'get_meps'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: { id: string }[] };
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
      expect(parsed.data.length).toBeGreaterThan(0);

      // Save MEP ID for dependent tests
      testMEPId = parsed.data[0]?.id ?? '';
      testMEPIds = parsed.data.map(m => m.id).filter(Boolean);
      expect(testMEPId).toBeTruthy();
    }, 90000);
  });

  describe('Core Tool: get_mep_details', () => {
    it('should return real MEP details from EP API', async (ctx) => {
      if (!testMEPId) {
        const meps = await retryOrSkip(() => handleGetMEPs({ limit: 1 }), 'setup');
        if (!meps) return;
        const data = JSON.parse(meps.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testMEPId = data.data[0]?.id ?? '';
      }

      const result = await retryOrSkip(
        () => handleGetMEPDetails({ id: testMEPId }),
        'get_mep_details'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { id: string; name: string };
      expect(parsed).toHaveProperty('id');
      expect(parsed).toHaveProperty('name');
      expect(typeof parsed.name).toBe('string');
    }, 120000);
  });

  describe('Core Tool: get_plenary_sessions', () => {
    it('should return real plenary session data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetPlenarySessions({ limit: 5 }),
        'get_plenary_sessions'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: { id: string }[] };
      expect(parsed).toHaveProperty('data');
      expect(parsed.data.length).toBeGreaterThan(0);

      // Save session ID for dependent tests
      testSessionId = parsed.data[0]?.id ?? '';
    }, 90000);
  });

  describe('Core Tool: get_voting_records', () => {
    it('should return real voting records data', async (ctx) => {
      if (!testSessionId) {
        const sessions = await retryOrSkip(() => handleGetPlenarySessions({ limit: 1 }), 'setup');
        if (!sessions) return;
        const data = JSON.parse(sessions.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testSessionId = data.data[0]?.id ?? '';
      }

      const result = await retryOrSkip(
        () => handleGetVotingRecords({ sessionId: testSessionId }),
        'get_voting_records'
      );
      if (!result) { ctx.skip(); return; }

      parseAndValidateNoMockData(result);
    }, 120000);
  });

  describe('Core Tool: search_documents', () => {
    it('should return real documents from EP API', async (ctx) => {
      const result = await retryOrSkip(
        () => handleSearchDocuments({ keyword: 'climate', dateFrom: '2025-01-01', dateTo: '2025-06-30', limit: 5 }),
        'search_documents'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { timedOut?: boolean; status?: string; data: { id: string }[] };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('data');
    }, 120000);
  });

  describe('Core Tool: get_committee_info', () => {
    it('should return real committee data from EP API', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetCommitteeInfo({ abbreviation: 'AFET' }),
        'get_committee_info'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as {
        timedOut?: boolean;
        status?: string;
      };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
    }, 180000);
  });

  describe('Core Tool: get_parliamentary_questions', () => {
    it('should return real parliamentary questions', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetParliamentaryQuestions({ limit: 5 }),
        'get_parliamentary_questions'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  // ══════════════════════════════════════════════════════════════
  // ADVANCED ANALYSIS TOOLS (3)
  // ══════════════════════════════════════════════════════════════

  describe('Advanced Tool: analyze_voting_patterns', () => {
    it('should analyze real voting patterns', async (ctx) => {
      if (!testMEPId) {
        const meps = await retryOrSkip(() => handleGetMEPs({ limit: 1 }), 'setup');
        if (!meps) return;
        const data = JSON.parse(meps.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testMEPId = data.data[0]?.id ?? '';
      }

      const result = await retryOrSkip(
        () => handleAnalyzeVotingPatterns({ mepId: testMEPId, dateFrom: '2024-01-01', dateTo: '2024-12-31' }),
        'analyze_voting_patterns'
      );
      if (!result) { ctx.skip(); return; }

      // EP API /meps/{id} does not expose voting stats, so the tool returns dataAvailable: false
      const parsed = parseAndValidateNoMockData(result) as { mepId: string; dataAvailable?: boolean; statistics?: unknown };
      expect(parsed).toHaveProperty('mepId');
      // Response may have statistics (if data available) or dataAvailable: false
      if (parsed.dataAvailable === false) {
        expect(parsed).toHaveProperty('message');
      } else {
        expect(parsed).toHaveProperty('statistics');
      }
    }, 120000);
  });

  describe('Advanced Tool: track_legislation', () => {
    it('should track real legislative procedure', async (ctx) => {
      // First get a real procedure ID
      if (!testProcedureId) {
        const procs = await retryOrSkip(() => handleGetProcedures({ limit: 1 }), 'setup');
        if (!procs) return;
        const data = JSON.parse(procs.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testProcedureId = data.data[0]?.id ?? '';
      }

      const result = await retryOrSkip(
        () => handleTrackLegislation({ procedureId: testProcedureId }),
        'track_legislation'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { procedureId: string; title: string; confidenceLevel: string; timedOut?: boolean; status?: string };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('procedureId');
      expect(parsed).toHaveProperty('title');
      expect(parsed.confidenceLevel).not.toBe('NONE');
    }, 120000);
  });

  describe('Advanced Tool: generate_report', () => {
    it('should generate real MEP activity report', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGenerateReport({ reportType: 'MEP_ACTIVITY' }),
        'generate_report'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as {
        timedOut?: boolean;
        status?: string;
      };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
    }, 120000);
  });

  // ══════════════════════════════════════════════════════════════
  // PHASE 1 OSINT INTELLIGENCE TOOLS (6)
  // ══════════════════════════════════════════════════════════════

  describe('OSINT Tool: assess_mep_influence', () => {
    it('should assess influence using real MEP data', async (ctx) => {
      if (!testMEPId) {
        const meps = await retryOrSkip(() => handleGetMEPs({ limit: 1 }), 'setup');
        if (!meps) return;
        const data = JSON.parse(meps.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testMEPId = data.data[0]?.id ?? '';
      }

      const result = await retryOrSkip(
        () => handleAssessMepInfluence({ mepId: testMEPId }),
        'assess_mep_influence'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { mepId: string; overallScore: number };
      expect(parsed).toHaveProperty('mepId');
      expect(parsed).toHaveProperty('overallScore');
      expect(typeof parsed.overallScore).toBe('number');
    }, 120000);
  });

  describe('OSINT Tool: analyze_coalition_dynamics', () => {
    it('should analyze coalition dynamics with real data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleAnalyzeCoalitionDynamics({ dateFrom: '2024-01-01', dateTo: '2024-12-31' }),
        'analyze_coalition_dynamics'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as {
        groupMetrics: unknown[];
        confidenceLevel: string;
        timedOut?: boolean;
        status?: string;
      };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('groupMetrics');
      expect(parsed).toHaveProperty('confidenceLevel');
    }, 180000);
  });

  describe('OSINT Tool: detect_voting_anomalies', () => {
    it('should detect anomalies using real voting data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleDetectVotingAnomalies({ dateFrom: '2024-01-01', dateTo: '2024-12-31' }),
        'detect_voting_anomalies'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { anomalies: unknown[] };
      expect(parsed).toHaveProperty('anomalies');
    }, 90000);
  });

  describe('OSINT Tool: compare_political_groups', () => {
    it('should compare groups using real data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleComparePoliticalGroups({ groupIds: ['EPP', 'S&D'], dateFrom: '2024-01-01', dateTo: '2024-12-31' }),
        'compare_political_groups'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as {
        groups: unknown[];
        timedOut?: boolean;
        status?: string;
      };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('groups');
    }, 120000);
  });

  describe('OSINT Tool: analyze_legislative_effectiveness', () => {
    it('should analyze effectiveness with real data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleAnalyzeLegislativeEffectiveness({ subjectType: 'COMMITTEE', subjectId: 'AFET', dateFrom: '2024-01-01', dateTo: '2024-12-31' }),
        'analyze_legislative_effectiveness'
      );
      if (!result) { ctx.skip(); return; }

      parseAndValidateNoMockData(result);
    }, 90000);
  });

  describe('OSINT Tool: monitor_legislative_pipeline', () => {
    it('should monitor pipeline with real procedure data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleMonitorLegislativePipeline({ status: 'ALL', limit: 5 }),
        'monitor_legislative_pipeline'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { pipeline: unknown[]; summary: unknown; methodology: string };
      expect(parsed).toHaveProperty('pipeline');
      expect(parsed).toHaveProperty('summary');
      expect(parsed.methodology).toContain('EP API');
    }, 90000);
  });

  // ══════════════════════════════════════════════════════════════
  // PHASE 2 OSINT INTELLIGENCE TOOLS (2)
  // ══════════════════════════════════════════════════════════════

  describe('OSINT Tool: analyze_committee_activity', () => {
    it('should analyze committee activity', async (ctx) => {
      const result = await retryOrSkip(
        () => handleAnalyzeCommitteeActivity({ committeeId: 'AFET' }),
        'analyze_committee_activity'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { committeeId: string };
      expect(parsed).toHaveProperty('committeeId');
    }, 90000);
  });

  describe('OSINT Tool: track_mep_attendance', () => {
    it('should track MEP attendance with real data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleTrackMepAttendance({ limit: 5 }),
        'track_mep_attendance'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as {
        timedOut?: boolean;
        status?: string;
      };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
    }, 90000);
  });

  // ══════════════════════════════════════════════════════════════
  // PHASE 3 OSINT INTELLIGENCE TOOLS (2)
  // ══════════════════════════════════════════════════════════════

  describe('OSINT Tool: analyze_country_delegation', () => {
    it('should analyze country delegation with real data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleAnalyzeCountryDelegation({ country: 'SE' }),
        'analyze_country_delegation'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as {
        country: string;
        timedOut?: boolean;
        status?: string;
      };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('country');
    }, 180000);
  });

  describe('OSINT Tool: generate_political_landscape', () => {
    it('should generate landscape with real data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGeneratePoliticalLandscape({}),
        'generate_political_landscape'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as {
        groups: unknown[];
        timedOut?: boolean;
        status?: string;
      };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('groups');
    }, 120000);
  });

  // ══════════════════════════════════════════════════════════════
  // PHASE 4 EP API v2 TOOLS (8)
  // ══════════════════════════════════════════════════════════════

  describe('Phase 4 Tool: get_current_meps', () => {
    it('should return real current MEPs', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetCurrentMEPs({ limit: 5 }),
        'get_current_meps'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 90000);
  });

  describe('Phase 4 Tool: get_speeches', () => {
    it('should return real speech data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetSpeeches({ limit: 5 }),
        'get_speeches'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 4 Tool: get_procedures', () => {
    it('should return real procedure data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetProcedures({ limit: 5 }),
        'get_procedures'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: { id: string }[] };
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
      if (parsed.data.length > 0) {
        testProcedureId = parsed.data[0]?.id ?? '';
      }
    }, 90000);
  });

  describe('Phase 4 Tool: get_adopted_texts', () => {
    it('should return real adopted texts', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetAdoptedTexts({ limit: 5 }),
        'get_adopted_texts'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 4 Tool: get_events', () => {
    it('should return real event data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetEvents({ limit: 5 }),
        'get_events'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 4 Tool: get_meeting_activities', () => {
    it('should return real meeting activity data', async (ctx) => {
      // get_meeting_activities requires a sittingId — fetch a real session ID first
      if (!testSessionId) {
        const sessions = await retryOrSkip(() => handleGetPlenarySessions({ limit: 1 }), 'setup session');
        if (!sessions) return;
        const data = JSON.parse(sessions.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testSessionId = data.data[0]?.id ?? '';
      }
      if (!testSessionId) { console.warn('[SKIP] No session ID available'); return; }

      const result = await retryOrSkip(
        () => handleGetMeetingActivities({ sittingId: testSessionId, limit: 5 }),
        'get_meeting_activities'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 120000);
  });

  describe('Phase 4 Tool: get_meeting_decisions', () => {
    it('should return real meeting decisions', async (ctx) => {
      // get_meeting_decisions requires a sittingId — fetch a real session ID first
      if (!testSessionId) {
        const sessions = await retryOrSkip(() => handleGetPlenarySessions({ limit: 1 }), 'setup session');
        if (!sessions) return;
        const data = JSON.parse(sessions.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testSessionId = data.data[0]?.id ?? '';
      }
      if (!testSessionId) { console.warn('[SKIP] No session ID available'); return; }

      const result = await retryOrSkip(
        () => handleGetMeetingDecisions({ sittingId: testSessionId, limit: 5 }),
        'get_meeting_decisions'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 120000);
  });

  describe('Phase 4 Tool: get_mep_declarations', () => {
    it('should return real MEP declarations', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetMEPDeclarations({ limit: 5 }),
        'get_mep_declarations'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  // ══════════════════════════════════════════════════════════════
  // PHASE 5 EP API v2 TOOLS (11)
  // ══════════════════════════════════════════════════════════════

  describe('Phase 5 Tool: get_incoming_meps', () => {
    it('should return real incoming MEPs data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetIncomingMEPs({ limit: 5 }),
        'get_incoming_meps'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 5 Tool: get_outgoing_meps', () => {
    it('should return real outgoing MEPs data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetOutgoingMEPs({ limit: 5 }),
        'get_outgoing_meps'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 5 Tool: get_homonym_meps', () => {
    it('should return real homonym MEPs data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetHomonymMEPs({ limit: 5 }),
        'get_homonym_meps'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 5 Tool: get_plenary_documents', () => {
    it('should return real plenary documents', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetPlenaryDocuments({ limit: 5 }),
        'get_plenary_documents'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 5 Tool: get_committee_documents', () => {
    it('should return real committee documents', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetCommitteeDocuments({ limit: 5 }),
        'get_committee_documents'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 5 Tool: get_plenary_session_documents', () => {
    it('should return real plenary session documents', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetPlenarySessionDocuments({ limit: 5 }),
        'get_plenary_session_documents'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 5 Tool: get_plenary_session_document_items', () => {
    it('should return real plenary session document items', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetPlenarySessionDocumentItems({ limit: 5 }),
        'get_plenary_session_document_items'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 5 Tool: get_controlled_vocabularies', () => {
    it('should return real controlled vocabularies', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetControlledVocabularies({ limit: 5 }),
        'get_controlled_vocabularies'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 5 Tool: get_external_documents', () => {
    it('should return real external documents', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetExternalDocuments({ limit: 5 }),
        'get_external_documents'
      );
      if (!result) { ctx.skip(); return; }

      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 90000);
  });

  describe('Phase 5 Tool: get_meeting_foreseen_activities', () => {
    it('should accept sittingId parameter', async (ctx) => {
      // This tool requires a sitting ID - get one from plenary sessions
      if (!testSessionId) {
        const sessions = await retryOrSkip(() => handleGetPlenarySessions({ limit: 1 }), 'setup');
        if (!sessions) return;
        const data = JSON.parse(sessions.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testSessionId = data.data[0]?.id ?? '';
      }

      const result = await retryOrSkip(
        () => handleGetMeetingForeseenActivities({ sittingId: testSessionId, limit: 5 }),
        'get_meeting_foreseen_activities'
      );
      if (!result) { ctx.skip(); return; }

      parseAndValidateNoMockData(result);
    }, 120000);
  });

  describe('Phase 5 Tool: get_procedure_events', () => {
    it('should return real procedure events', async (ctx) => {
      if (!testProcedureId) {
        const procs = await retryOrSkip(() => handleGetProcedures({ limit: 1 }), 'setup');
        if (!procs) return;
        const data = JSON.parse(procs.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testProcedureId = data.data[0]?.id ?? '';
      }

      const result = await retryOrSkip(
        () => handleGetProcedureEvents({ processId: testProcedureId, limit: 5 }),
        'get_procedure_events'
      );
      if (!result) { ctx.skip(); return; }

      parseAndValidateNoMockData(result);
    }, 120000);
  });

  // ══════════════════════════════════════════════════════════════
  // PHASE 6 ADVANCED OSINT TOOLS (4)
  // ══════════════════════════════════════════════════════════════

  describe('Phase 6 OSINT Tool: network_analysis', () => {
    it('should return network analysis data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleNetworkAnalysis({}),
        'network_analysis'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { networkNodes: unknown; networkEdges: unknown; dataAvailable?: boolean };
      if (parsed.dataAvailable === false) { ctx.skip(); return; }
      expect(parsed).toHaveProperty('networkNodes');
      expect(parsed).toHaveProperty('networkEdges');
    }, 90000);
  });

  describe('Phase 6 OSINT Tool: sentiment_tracker', () => {
    it('should return sentiment tracking data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleSentimentTracker({}),
        'sentiment_tracker'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as {
        groupSentiments: unknown;
        polarizationIndex: unknown;
        timedOut?: boolean;
        status?: string;
      };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('groupSentiments');
      expect(parsed).toHaveProperty('polarizationIndex');
    }, 120000);
  });

  describe('Phase 6 OSINT Tool: early_warning_system', () => {
    it('should return early warning data', async (ctx) => {
      const result = await retryOrSkip(
        () => handleEarlyWarningSystem({}),
        'early_warning_system'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { warnings: unknown; trendIndicators: unknown; dataAvailable?: boolean };
      if (parsed.dataAvailable === false) { ctx.skip(); return; }
      expect(parsed).toHaveProperty('warnings');
      expect(parsed).toHaveProperty('trendIndicators');
    }, 90000);
  });

  describe('Phase 6 OSINT Tool: comparative_intelligence', () => {
    it('should return comparative intelligence data', async (ctx) => {
      // Use dynamically discovered MEP IDs to avoid stale hardcoded IDs returning 404
      const numericIds = resolveNumericMepIds(testMEPId, 2, testMEPIds);
      if (numericIds.length < 2) { ctx.skip(); return; }

      const result = await retryOrSkip(
        () => handleComparativeIntelligence({ mepIds: numericIds }),
        'comparative_intelligence'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as {
        profiles: unknown;
        correlationMatrix: unknown;
        timedOut?: boolean;
        status?: string;
      };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('profiles');
      expect(parsed).toHaveProperty('correlationMatrix');
    }, 90000);
  });

  describe('OSINT Correlation Tool: correlate_intelligence', () => {
    it('should return correlation analysis data', async (ctx) => {
      // Use dynamically discovered MEP IDs to avoid stale hardcoded IDs returning 404
      const numericIds = resolveNumericMepIds(testMEPId, 2, testMEPIds);
      if (numericIds.length < 2) { ctx.skip(); return; }
      const stringIds = numericIds.map(String);

      const result = await retryOrSkip(
        () => handleCorrelateIntelligence({ mepIds: stringIds }),
        'correlate_intelligence'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as {
        alerts: unknown;
        summary: unknown;
        timedOut?: boolean;
        status?: string;
      };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('alerts');
      expect(parsed).toHaveProperty('summary');
    }, 120000);
  });

  describe('Phase 5 Tool: get_meeting_plenary_session_documents', () => {
    it('should return meeting plenary session documents', async (ctx) => {
      if (!testSessionId) {
        const sessions = await retryOrSkip(() => handleGetPlenarySessions({ limit: 1 }), 'setup');
        if (!sessions) return;
        const data = JSON.parse(sessions.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testSessionId = data.data[0]?.id ?? '';
      }
      if (!testSessionId) return;

      const result = await retryOrSkip(
        () => handleGetMeetingPlenarySessionDocuments({ sittingId: testSessionId, limit: 5 }),
        'get_meeting_plenary_session_documents'
      );
      if (!result) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 120000);
  });

  describe('Phase 5 Tool: get_meeting_plenary_session_document_items', () => {
    it('should return meeting plenary session document items', async (ctx) => {
      if (!testSessionId) {
        const sessions = await retryOrSkip(() => handleGetPlenarySessions({ limit: 1 }), 'setup');
        if (!sessions) return;
        const data = JSON.parse(sessions.content[0]?.text ?? '{}') as { data: { id: string }[] };
        testSessionId = data.data[0]?.id ?? '';
      }
      if (!testSessionId) return;

      const result = await retryOrSkip(
        () => handleGetMeetingPlenarySessionDocumentItems({ sittingId: testSessionId, limit: 5 }),
        'get_meeting_plenary_session_document_items'
      );
      if (!result) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { data: unknown[] };
      expect(parsed).toHaveProperty('data');
    }, 120000);
  });

  // ═══════════════════════════════════════════════════════════════════
  //  Feed Endpoint Tools (13 tools)
  // ═══════════════════════════════════════════════════════════════════

  describe('Feed Tool: get_meps_feed', () => {
    it('should return recently updated MEPs', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetMEPsFeed({ timeframe: 'one-week' }),
        'get_meps_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { data: unknown[]; dataQualityWarnings?: string[] };
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 120000);
  });

  describe('Feed Tool: get_events_feed', () => {
    it('should return recently updated events', async (ctx) => {
      // Use 'one-week' to avoid slow 'one-month' endpoint
      const result = await retryOrSkip(
        () => handleGetEventsFeed({ timeframe: 'one-week' }),
        'get_events_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as Record<string, unknown>;
      // Skip for transient upstream errors (e.g. 404/503 from EP API)
      if (typeof parsed === 'object' && parsed !== null && 'error' in parsed) { ctx.skip(); return; }
      // Fail with a clear message for genuinely unexpected response shapes
      if (!(typeof parsed === 'object' && parsed !== null && 'data' in parsed)) {
        expect.fail(`Expected parsed response to be an object with a 'data' property, got: ${JSON.stringify(parsed).substring(0, 200)}`);
      }
      expect(Array.isArray(parsed['data'])).toBe(true);
    }, 180000);
  });

  describe('Feed Tool: get_procedures_feed', () => {
    it('should return recently updated procedures', async (ctx) => {
      // Use 'one-week' to avoid slow 'one-month' endpoint
      const result = await retryOrSkip(
        () => handleGetProceduresFeed({ timeframe: 'one-week' }),
        'get_procedures_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as Record<string, unknown>;
      // Skip for transient upstream errors (e.g. 404/503 from EP API)
      if (typeof parsed === 'object' && parsed !== null && 'error' in parsed) { ctx.skip(); return; }
      // Fail with a clear message for genuinely unexpected response shapes
      if (!(typeof parsed === 'object' && parsed !== null && 'data' in parsed)) {
        expect.fail(`Expected parsed response to be an object with a 'data' property, got: ${JSON.stringify(parsed).substring(0, 200)}`);
      }
      expect(Array.isArray(parsed['data'])).toBe(true);
    }, 180000);
  });

  describe('Feed Tool: get_adopted_texts_feed', () => {
    it('should return recently updated adopted texts', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetAdoptedTextsFeed({ timeframe: 'one-week' }),
        'get_adopted_texts_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { data: unknown[]; dataQualityWarnings?: string[] };
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 120000);
  });

  describe('Feed Tool: get_mep_declarations_feed', () => {
    it('should return recently updated MEP declarations', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetMEPDeclarationsFeed({ timeframe: 'one-week' }),
        'get_mep_declarations_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { data: unknown[]; dataQualityWarnings?: string[] };
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 120000);
  });

  describe('Feed Tool: get_documents_feed', () => {
    it('should return recently updated documents', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetDocumentsFeed({}),
        'get_documents_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { timedOut?: boolean; status?: string; data: unknown[]; dataQualityWarnings?: string[] };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 180000);
  });

  describe('Feed Tool: get_plenary_documents_feed', () => {
    it('should return recently updated plenary documents', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetPlenaryDocumentsFeed({}),
        'get_plenary_documents_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { timedOut?: boolean; status?: string; data: unknown[]; dataQualityWarnings?: string[] };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 180000);
  });

  describe('Feed Tool: get_committee_documents_feed', () => {
    it('should return recently updated committee documents', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetCommitteeDocumentsFeed({}),
        'get_committee_documents_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { timedOut?: boolean; status?: string; data: unknown[]; dataQualityWarnings?: string[] };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 180000);
  });

  describe('Feed Tool: get_plenary_session_documents_feed', () => {
    it('should return recently updated plenary session documents', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetPlenarySessionDocumentsFeed({}),
        'get_plenary_session_documents_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { timedOut?: boolean; status?: string; data: unknown[]; dataQualityWarnings?: string[] };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 180000);
  });

  describe('Feed Tool: get_external_documents_feed', () => {
    it('should return recently updated external documents', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetExternalDocumentsFeed({ timeframe: 'one-week' }),
        'get_external_documents_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { data: unknown[]; dataQualityWarnings?: string[] };
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 120000);
  });

  describe('Feed Tool: get_parliamentary_questions_feed', () => {
    it('should return recently updated parliamentary questions', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetParliamentaryQuestionsFeed({}),
        'get_parliamentary_questions_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { timedOut?: boolean; status?: string; data: unknown[]; dataQualityWarnings?: string[] };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 180000);
  });

  describe('Feed Tool: get_corporate_bodies_feed', () => {
    it('should return recently updated corporate bodies', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetCorporateBodiesFeed({}),
        'get_corporate_bodies_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { timedOut?: boolean; status?: string; data: unknown[]; dataQualityWarnings?: string[] };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 180000);
  });

  describe('Feed Tool: get_controlled_vocabularies_feed', () => {
    it('should return recently updated controlled vocabularies', async (ctx) => {
      const result = await retryOrSkip(
        () => handleGetControlledVocabulariesFeed({}),
        'get_controlled_vocabularies_feed'
      );
      if (!result) { ctx.skip(); return; }
      if (result.isError === true) { ctx.skip(); return; }
      const parsed = parseAndValidateNoMockData(result) as { timedOut?: boolean; status?: string; data: unknown[]; dataQualityWarnings?: string[] };
      if (parsed.timedOut === true || parsed.status === 'timeout') { ctx.skip(); return; }
      expect(parsed).toHaveProperty('data');
      expect(Array.isArray(parsed.data)).toBe(true);
    }, 120000);
  });
});
