/**
 * Precomputed European Parliament activity statistics (2004–2026).
 *
 * This module contains static, pre-generated summary statistics for
 * European Parliament activity aggregated by year and month. Data
 * is sourced from the European Parliament Open Data Portal and is
 * designed to be refreshed weekly by an agentic workflow.
 *
 * Covers parliamentary terms EP6 (2004-2009) through EP10 (2024-2029).
 *
 * ISMS Policy: SC-002 (Input Validation), PR-001 (Data Minimisation)
 * Data source: European Parliament Open Data Portal — data.europarl.europa.eu
 *
 * @module data/generatedStats
 */

/** Monthly breakdown of European Parliament activity for a single calendar month. */
export interface MonthlyActivity {
  /** Calendar month (1–12) */
  month: number;
  /** Number of plenary sessions held */
  plenarySessions: number;
  /** Legislative acts adopted */
  legislativeActsAdopted: number;
  /** Roll-call votes conducted */
  rollCallVotes: number;
  /** Committee meetings held */
  committeeMeetings: number;
  /** Parliamentary questions tabled */
  parliamentaryQuestions: number;
  /** Resolutions adopted */
  resolutions: number;
  /** Speeches delivered in plenary */
  speeches: number;
  /** Texts adopted (reports, opinions, etc.) */
  adoptedTexts: number;
  /** Legislative procedures tracked */
  procedures: number;
  /** Parliamentary events */
  events: number;
  /** Documents produced (plenary + committee + external) */
  documents: number;
  /** MEP turnover (incoming + outgoing) */
  mepTurnover: number;
  /** MEP financial/interest declarations filed */
  declarations: number;
}

/** Snapshot of a single political group's representation in a given year. */
export interface PoliticalGroupSnapshot {
  /** Political group short name (e.g. 'EPP', 'S&D', 'NI') */
  name: string;
  /** Number of seats held */
  seats: number;
  /** Seat share as a percentage (0–100) */
  seatShare: number;
}

/**
 * Snapshot of the political landscape of the European Parliament for a
 * single year: composition of political groups, fragmentation metrics,
 * coalition viability indicators, and turnover statistics.
 *
 * Used by {@link GENERATED_STATS} as the per-year landscape record and
 * surfaced by the `get_all_generated_stats` MCP tool.
 */
export interface PoliticalLandscapeData {
  /**
   * Political groups in the parliament for this year.
   *
   * This array includes all recognised political groups and may also
   * contain an `NI` (non-attached members) entry when applicable.
   * The `NI` entry represents MEPs not attached to any political group
   * and is not counted in `totalGroups`.
   */
  groups: PoliticalGroupSnapshot[];
  /**
   * Total number of recognised political groups (excluding non-attached
   * members, i.e. the `NI` entry in `groups` when present).
   */
  totalGroups: number;
  /** Largest group name */
  largestGroup: string;
  /** Largest group seat share (0–100) */
  largestGroupSeatShare: number;
  /** Effective Number of Parliamentary Parties (Laakso-Taagepera index) */
  fragmentationIndex: number;
  /** Whether any two groups can form a majority */
  grandCoalitionPossible: boolean;
  /** Political balance: centre-right vs centre-left vs other */
  politicalBalance: string;
}

/** Multi-axis ideological position for a political group. */
interface GroupCompassPosition {
  /** Economic axis: 0 = far-left (interventionist), 10 = far-right (free-market) */
  economic: number;
  /** Social axis: 0 = libertarian (civil liberties), 10 = authoritarian (state control) */
  social: number;
  /** EU integration axis: 0 = hard eurosceptic, 10 = federalist */
  euIntegration: number;
}

/**
 * Political compass positions by EP group name.
 * Based on Chapel Hill Expert Survey (CHES) methodology with EP voting behaviour adjustments.
 */
const GROUP_COMPASS: Record<string, GroupCompassPosition> = {
  'GUE/NGL':  { economic: 1.5, social: 3.0, euIntegration: 4.0 },
  'The Left': { economic: 1.5, social: 3.0, euIntegration: 4.0 },
  'PES':      { economic: 3.5, social: 4.0, euIntegration: 7.5 },
  'S&D':      { economic: 3.5, social: 4.0, euIntegration: 7.5 },
  'Greens/EFA': { economic: 3.0, social: 2.0, euIntegration: 8.0 },
  'ALDE':     { economic: 6.0, social: 3.0, euIntegration: 8.5 },
  'RE':       { economic: 6.0, social: 3.0, euIntegration: 8.5 },
  'EPP':      { economic: 6.5, social: 5.5, euIntegration: 7.5 },
  'EPP-ED':   { economic: 6.5, social: 5.5, euIntegration: 7.5 },
  'ECR':      { economic: 7.5, social: 7.0, euIntegration: 3.5 },
  'UEN':      { economic: 7.0, social: 7.5, euIntegration: 3.0 },
  'IND/DEM':  { economic: 6.5, social: 7.0, euIntegration: 1.5 },
  'EFD':      { economic: 7.0, social: 7.0, euIntegration: 1.5 },
  'EFDD':     { economic: 7.0, social: 7.0, euIntegration: 1.5 },
  'ENF':      { economic: 5.5, social: 8.0, euIntegration: 1.0 },
  'ID':       { economic: 5.5, social: 8.0, euIntegration: 1.0 },
  'PfE':      { economic: 5.5, social: 8.0, euIntegration: 1.0 },
  'ESN':      { economic: 5.0, social: 9.0, euIntegration: 0.5 },
};

/**
 * Political compass quadrant (2D: economic × social axes).
 *
 * ```
 *              LIBERTARIAN
 *          ┌───────┬───────┐
 *          │ Lib-  │ Lib-  │
 *   LEFT   │ Left  │ Right │  RIGHT
 * economic │       │       │ economic
 *          ├───────┼───────┤
 *          │ Auth- │ Auth- │
 *          │ Left  │ Right │
 *          └───────┴───────┘
 *             AUTHORITARIAN
 * ```
 */
export type PoliticalQuadrant =
  | 'libertarianLeft'
  | 'libertarianRight'
  | 'authoritarianLeft'
  | 'authoritarianRight';

/** Seat share distribution across the 4 political compass quadrants. */
export interface QuadrantDistribution {
  /** Libertarian-Left: civil liberties + economic intervention (Greens, radical left) */
  libertarianLeft: number;
  /** Libertarian-Right: civil liberties + free market (liberals) */
  libertarianRight: number;
  /** Authoritarian-Left: state control + economic intervention (none currently in EP) */
  authoritarianLeft: number;
  /** Authoritarian-Right: state control + free market/nationalism (ECR, far-right) */
  authoritarianRight: number;
}

/** Multi-dimensional political compass analysis for the European Parliament. */
export interface PoliticalCompassAnalysis {
  /** Seat-share-weighted economic position (0 = far-left, 10 = far-right) */
  parliamentEconomicPosition: number;
  /** Seat-share-weighted social position (0 = libertarian, 10 = authoritarian) */
  parliamentSocialPosition: number;
  /** Seat-share-weighted EU integration position (0 = eurosceptic, 10 = federalist) */
  parliamentEuPosition: number;
  /** Seat-share distribution across the four political compass quadrants (%) */
  quadrantDistribution: QuadrantDistribution;
  /** Dominant quadrant by seat share */
  dominantQuadrant: PoliticalQuadrant;
  /** Authoritarian-libertarian tension: stdDev of social axis scores weighted by seats */
  authLibTension: number;
  /** Economic left-right polarisation: stdDev of economic axis scores weighted by seats */
  economicPolarisation: number;
  /** EU integration consensus: stdDev of EU integration scores weighted by seats */
  euIntegrationDispersion: number;
}

/** Combined political balance analysis: 1D blocs + 2D compass + EU axis. */
export interface PoliticalBlocAnalysis {
  /** Combined seat share of left-wing groups (S&D, GUE/NGL, Greens/EFA) */
  leftBlocShare: number;
  /** Combined seat share of centre/liberal groups (ALDE, RE) */
  centreBlocShare: number;
  /** Combined seat share of centre-right + right groups (EPP, ECR, UEN, far-right) */
  rightBlocShare: number;
  /** Combined seat share of far-right/eurosceptic groups (ID, PfE, ESN, etc.) */
  euroscepticShare: number;
  /** Bipolar index: (right - left) / (right + left); range -1 (left) to +1 (right) */
  bipolarIndex: number;

  /** Three-axis political compass analysis (economic × social × EU integration) */
  politicalCompass: PoliticalCompassAnalysis;
}

/** Derived OSINT intelligence metrics computed from raw EP activity data. */
export interface DerivedIntelligenceMetrics {
  /** Legislative acts adopted per plenary session */
  legislativeOutputPerSession: number;
  /** Legislative acts adopted per MEP (per-capita productivity) */
  legislativeOutputPerMEP: number;
  /** Fraction of roll-call votes producing legislation (%) */
  rollCallVoteYield: number;
  /** Fraction of procedures resulting in adopted legislation (%) */
  procedureCompletionRate: number;
  /** Ratio of resolutions (non-binding) to legislative acts (binding) */
  resolutionToLegislationRatio: number;
  /** Documents produced per legislative act adopted */
  documentBurdenPerAct: number;

  /** Parliamentary questions per MEP (oversight intensity) */
  mepOversightIntensity: number;
  /** Speeches per MEP (debate participation rate) */
  mepSpeechRate: number;
  /** Speeches per plenary session (debate intensity) */
  debateIntensityPerSession: number;
  /** Parliamentary questions per plenary session (oversight tempo) */
  oversightPerSession: number;

  /** Top-2 groups combined seat share (%) — grand coalition viability */
  topTwoGroupsConcentration: number;
  /** Top-3 groups combined seat share (%) — minimum viable coalition */
  topThreeGroupsConcentration: number;
  /** Herfindahl-Hirschman Index — standard market concentration metric */
  herfindahlHirschmanIndex: number;
  /** Largest group seat share / second-largest group seat share */
  dominanceRatio: number;
  /** Percentage points the largest group is from 50% majority */
  majorityThresholdGap: number;
  /** Fewest groups needed to form a majority (cumulative > 50%) */
  minimumWinningCoalitionSize: number;
  /** Top-2 groups combined seat share minus 50 (positive = surplus, negative = deficit) */
  grandCoalitionSurplusDeficit: number;
  /** Non-attached (NI) members seat share (%) — parliamentary marginalization */
  nonAttachedShare: number;
  /** Effective opposition parties: ENPP minus 1 */
  effectiveOppositionParties: number;

  /** Political bloc analysis with left/centre/right seat shares */
  politicalBlocAnalysis: PoliticalBlocAnalysis;

  /** Stability index: 1 - (turnover / mepCount); below 0.5 = election year */
  mepStabilityIndex: number;
  /** Turnover rate as percentage of total MEPs */
  turnoverRate: number;
  /** Institutional memory risk classification */
  institutionalMemoryRisk: 'HIGH' | 'MEDIUM' | 'LOW';
  /** Declarations per MEP — transparency/accountability indicator */
  declarationCoverageRatio: number;

  /** YoY percentage change in legislative acts adopted */
  legislativeOutputChange: number | null;
  /** YoY change in ENPP (fragmentation velocity) */
  fragmentationVelocity: number | null;
  /** YoY percentage change in parliamentary questions */
  questionsChange: number | null;

  /** Parliamentary questions per legislative act (oversight vs. lawmaking) */
  oversightToLegislationBalance: number;
  /** Speeches per roll-call vote (debate intensity relative to decisions) */
  speechToVoteRatio: number;
  /** Committee meetings per plenary session (preparatory work depth) */
  committeeToPlenaryRatio: number;
}

/** Aggregated annual statistics for a single calendar year of EP activity. */
export interface YearlyStats {
  /** Calendar year (e.g. 2004) */
  year: number;
  /** Parliamentary term identifier (e.g. 'EP6', 'EP9/EP10 transition') */
  parliamentaryTerm: string;
  /** Total number of MEPs in office */
  mepCount: number;
  /** Number of plenary sessions held */
  plenarySessions: number;
  /** Legislative acts adopted */
  legislativeActsAdopted: number;
  /** Roll-call votes conducted */
  rollCallVotes: number;
  /** Committee meetings held */
  committeeMeetings: number;
  /** Parliamentary questions tabled */
  parliamentaryQuestions: number;
  /** Resolutions adopted */
  resolutions: number;
  /** Speeches delivered in plenary */
  speeches: number;
  /** Texts adopted (reports, opinions, etc.) */
  adoptedTexts: number;
  /** Legislative procedures tracked (get_procedures, get_procedure_events) */
  procedures: number;
  /** Parliamentary events (get_events) */
  events: number;
  /** Total documents: plenary + committee + external (get_plenary_documents, get_committee_documents, get_external_documents) */
  documents: number;
  /** MEP turnover: incoming + outgoing (get_incoming_meps, get_outgoing_meps) */
  mepTurnover: number;
  /** MEP financial/interest declarations (get_mep_declarations) */
  declarations: number;
  /** Month-by-month activity breakdown (12 entries, Jan–Dec) */
  monthlyActivity: MonthlyActivity[];
  /** Political landscape snapshot for the year */
  politicalLandscape: PoliticalLandscapeData;
  /** Notable events and key developments during the year */
  commentary: string;
  /** OSINT-derived intelligence metrics computed from raw activity data */
  derivedIntelligence: DerivedIntelligenceMetrics;
}

/** Ranked year entry within a category ranking. */
export interface RankedYear {
  /** Calendar year */
  year: number;
  /** Rank among all years (1 = highest activity) */
  rank: number;
  /** Percentile score (0–100) */
  percentile: number;
  /** Sum of the metric value used for ranking */
  totalActivityScore: number;
}

/** Statistical ranking of years for a single activity category. */
export interface CategoryRanking {
  /** Human-readable category label (e.g. 'Plenary Sessions') */
  category: string;
  /** Per-year ranking entries, sorted by descending activity score */
  rankings: RankedYear[];
  /** Mean value across all years */
  mean: number;
  /** Standard deviation */
  stdDev: number;
  /** Median value */
  median: number;
  /** Year with the highest activity score */
  topYear: number;
  /** Year with the lowest activity score */
  bottomYear: number;
}

/**
 * Predicted activity metrics for a future year.
 *
 * Values are computed using average-based extrapolation from the 2021–2025
 * baseline, adjusted by parliamentary term cycle factors that model the
 * typical ramp-up → peak → decline pattern within each five-year term.
 */
export interface PredictionYear {
  /** Predicted calendar year (2027–2031) */
  year: number;
  /** Predicted plenary sessions */
  predictedPlenarySessions: number;
  /** Predicted legislative acts adopted */
  predictedLegislativeActs: number;
  /** Predicted roll-call votes */
  predictedRollCallVotes: number;
  /** Predicted committee meetings */
  predictedCommitteeMeetings: number;
  /** Predicted parliamentary questions */
  predictedParliamentaryQuestions: number;
  /** Predicted resolutions */
  predictedResolutions: number;
  /** Predicted speeches */
  predictedSpeeches: number;
  /** Predicted adopted texts */
  predictedAdoptedTexts: number;
  /** Predicted procedures */
  predictedProcedures: number;
  /** Predicted events */
  predictedEvents: number;
  /** Predicted documents */
  predictedDocuments: number;
  /** Predicted MEP turnover */
  predictedMepTurnover: number;
  /** Predicted declarations */
  predictedDeclarations: number;
  /** Confidence interval string (e.g. '±12%') */
  confidenceInterval: string;
  /** Description of the prediction methodology for this year */
  methodology: string;
}

/** Top-level container for all precomputed European Parliament statistics. */
export interface GeneratedStatsData {
  /** ISO 8601 timestamp of when stats were last generated */
  generatedAt: string;
  /** Underlying dataset coverage period (always 2004–2026) */
  coveragePeriod: { from: number; to: number };
  /** Version of the stats generation methodology */
  methodologyVersion: string;
  /** Attribution string for the data source */
  dataSource: string;
  /** Annual statistics for each year in the coverage period */
  yearlyStats: YearlyStats[];
  /** Per-category statistical rankings across years */
  categoryRankings: CategoryRanking[];
  /** Predicted activity for future years (2027–2031) */
  predictions: PredictionYear[];
  /** High-level analytical summary of trends and key findings */
  analysisSummary: {
    /** Overall multi-year trend description */
    overallTrend: string;
    /** Year with the highest total activity */
    peakActivityYear: number;
    /** Year with the lowest total activity */
    lowestActivityYear: number;
    /** Mean annual legislative output across all years */
    averageAnnualLegislativeOutput: number;
    /** Long-term legislative productivity trend description */
    legislativeProductivityTrend: string;
    /** Notable analytical findings */
    keyFindings: string[];
  };
}

const MONTHLY_WEIGHTS = [
  0.07,
  0.09,
  0.10,
  0.09,
  0.09,
  0.08,
  0.07,
  0.01,
  0.09,
  0.10,
  0.11,
  0.10,
];

/**
 * Distribute an annual total across 12 months using MONTHLY_WEIGHTS,
 * ensuring that the resulting monthly integers sum exactly to the total.
 */
function distributeMetric(total: number): number[] {
  if (total <= 0) {
    return MONTHLY_WEIGHTS.map(() => 0);
  }

  const raw: number[] = MONTHLY_WEIGHTS.map((w) => total * w);
  const base: number[] = raw.map((value) => Math.floor(value));
  const baseSum = base.reduce((acc, value) => acc + value, 0);
  const remainder = total - baseSum;

  if (remainder > 0) {
    const indices = raw
      .map((value, index) => ({ index, frac: value - (base[index] ?? 0) }))
      .sort((a, b) => b.frac - a.frac)
      .map((item) => item.index);

    for (let i = 0; i < remainder && i < indices.length; i++) {
      const idx = indices[i];
      if (idx !== undefined && base[idx] !== undefined) {
        base[idx] += 1;
      }
    }
  }

  return base;
}

function distributeMonthly(annual: Omit<YearlyStats, 'monthlyActivity' | 'politicalLandscape' | 'derivedIntelligence'>): MonthlyActivity[] {
  const realMonthly = RAW_MONTHLY_DATA[annual.year];

  /** Return real monthly data for a metric if available, otherwise use synthetic distribution. */
  const getMonthly = (key: string, total: number): number[] => {
    const real = realMonthly?.[key];
    if (real?.length === 12) return real;
    return distributeMetric(total);
  };

  const metrics: Record<string, number[]> = {
    plenarySessions: getMonthly('plenarySessions', annual.plenarySessions),
    legislativeActsAdopted: distributeMetric(annual.legislativeActsAdopted),
    rollCallVotes: distributeMetric(annual.rollCallVotes),
    committeeMeetings: distributeMetric(annual.committeeMeetings),
    parliamentaryQuestions: distributeMetric(annual.parliamentaryQuestions),
    resolutions: distributeMetric(annual.resolutions),
    speeches: getMonthly('speeches', annual.speeches),
    adoptedTexts: distributeMetric(annual.adoptedTexts),
    procedures: distributeMetric(annual.procedures),
    events: getMonthly('events', annual.events),
    documents: distributeMetric(annual.documents),
    mepTurnover: distributeMetric(annual.mepTurnover),
    declarations: distributeMetric(annual.declarations),
  };

  const at = (key: string, i: number): number => metrics[key]?.[i] ?? 0;

  return MONTHLY_WEIGHTS.map((_, i) => ({
    month: i + 1,
    plenarySessions: at('plenarySessions', i),
    legislativeActsAdopted: at('legislativeActsAdopted', i),
    rollCallVotes: at('rollCallVotes', i),
    committeeMeetings: at('committeeMeetings', i),
    parliamentaryQuestions: at('parliamentaryQuestions', i),
    resolutions: at('resolutions', i),
    speeches: at('speeches', i),
    adoptedTexts: at('adoptedTexts', i),
    procedures: at('procedures', i),
    events: at('events', i),
    documents: at('documents', i),
    mepTurnover: at('mepTurnover', i),
    declarations: at('declarations', i),
  }));
}

const RAW_YEARLY: Omit<YearlyStats, 'monthlyActivity' | 'politicalLandscape' | 'derivedIntelligence'>[] = [
  { year: 2004, parliamentaryTerm: 'EP6 (2004-2009)', mepCount: 732, plenarySessions: 42, legislativeActsAdopted: 68, rollCallVotes: 356, committeeMeetings: 1820, parliamentaryQuestions: 4215, resolutions: 120, speeches: 8500, adoptedTexts: 85, procedures: 511, events: 1189, documents: 2647, mepTurnover: 385, declarations: 580, commentary: 'EP6 began with the 2004 enlargement (10 new member states). Transition year with new MEPs, committee formation, and establishment of working relationships in an expanded Parliament of 25 member states.' },
  { year: 2005, parliamentaryTerm: 'EP6 (2004-2009)', mepCount: 732, plenarySessions: 48, legislativeActsAdopted: 82, rollCallVotes: 412, committeeMeetings: 2050, parliamentaryQuestions: 4580, resolutions: 145, speeches: 10200, adoptedTexts: 102, procedures: 565, events: 1245, documents: 2964, mepTurnover: 42, declarations: 620, commentary: 'Full operational year of EP6. REACH chemicals regulation debate began. Constitutional Treaty rejected by French and Dutch referendums, impacting EU institutional dynamics.' },
  { year: 2006, parliamentaryTerm: 'EP6 (2004-2009)', mepCount: 732, plenarySessions: 50, legislativeActsAdopted: 95, rollCallVotes: 448, committeeMeetings: 2120, parliamentaryQuestions: 4780, resolutions: 158, speeches: 11500, adoptedTexts: 118, procedures: 634, events: 1599, documents: 3373, mepTurnover: 38, declarations: 645, commentary: 'Services Directive (Bolkestein) adopted after significant amendments. Parliament asserted co-decision powers. Bulgaria and Romania accession preparations intensified.' },
  { year: 2007, parliamentaryTerm: 'EP6 (2004-2009)', mepCount: 785, plenarySessions: 52, legislativeActsAdopted: 110, rollCallVotes: 520, committeeMeetings: 2280, parliamentaryQuestions: 5120, resolutions: 172, speeches: 12800, adoptedTexts: 135, procedures: 646, events: 1410, documents: 3404, mepTurnover: 95, declarations: 710, commentary: 'Bulgaria and Romania joined the EU (January), increasing MEP count to 785. Lisbon Treaty negotiations. High legislative output as EP6 matured.' },
  { year: 2008, parliamentaryTerm: 'EP6 (2004-2009)', mepCount: 785, plenarySessions: 50, legislativeActsAdopted: 125, rollCallVotes: 560, committeeMeetings: 2350, parliamentaryQuestions: 5380, resolutions: 185, speeches: 13500, adoptedTexts: 152, procedures: 671, events: 1600, documents: 3417, mepTurnover: 35, declarations: 690, commentary: 'Peak activity year for EP6. Climate and energy package negotiations. Financial crisis response dominated second half. Irish referendum rejected Lisbon Treaty initially.' },
  { year: 2009, parliamentaryTerm: 'EP6/EP7 transition', mepCount: 736, plenarySessions: 38, legislativeActsAdopted: 72, rollCallVotes: 380, committeeMeetings: 1650, parliamentaryQuestions: 3850, resolutions: 105, speeches: 7200, adoptedTexts: 78, procedures: 647, events: 1558, documents: 3325, mepTurnover: 420, declarations: 520, commentary: 'EP6/EP7 transition year. European elections in June 2009. Reduced output due to election period. Lisbon Treaty entered into force December 2009, expanding Parliament\'s powers.' },
  { year: 2010, parliamentaryTerm: 'EP7 (2009-2014)', mepCount: 736, plenarySessions: 48, legislativeActsAdopted: 88, rollCallVotes: 480, committeeMeetings: 2100, parliamentaryQuestions: 4920, resolutions: 155, speeches: 11000, adoptedTexts: 108, procedures: 909, events: 1389, documents: 3245, mepTurnover: 48, declarations: 650, commentary: 'First full year under Lisbon Treaty. Parliament gained co-decision (now "ordinary legislative procedure") on most policy areas. Eurozone debt crisis response began.' },
  { year: 2011, parliamentaryTerm: 'EP7 (2009-2014)', mepCount: 754, plenarySessions: 52, legislativeActsAdopted: 108, rollCallVotes: 550, committeeMeetings: 2320, parliamentaryQuestions: 5450, resolutions: 178, speeches: 12500, adoptedTexts: 132, procedures: 957, events: 1550, documents: 3351, mepTurnover: 52, declarations: 680, commentary: 'Croatia accession preparations. Six-Pack economic governance legislation adopted. Parliament exercised new budgetary powers under Lisbon Treaty. Arab Spring response.' },
  { year: 2012, parliamentaryTerm: 'EP7 (2009-2014)', mepCount: 754, plenarySessions: 50, legislativeActsAdopted: 118, rollCallVotes: 580, committeeMeetings: 2380, parliamentaryQuestions: 5680, resolutions: 188, speeches: 13000, adoptedTexts: 145, procedures: 816, events: 1417, documents: 3308, mepTurnover: 40, declarations: 695, commentary: 'Fiscal Compact negotiations. Banking union proposals. Two-Pack economic governance. Parliament strengthened oversight of EU economic governance framework.' },
  { year: 2013, parliamentaryTerm: 'EP7 (2009-2014)', mepCount: 766, plenarySessions: 54, legislativeActsAdopted: 135, rollCallVotes: 620, committeeMeetings: 2500, parliamentaryQuestions: 5920, resolutions: 205, speeches: 14200, adoptedTexts: 168, procedures: 946, events: 1682, documents: 3428, mepTurnover: 55, declarations: 720, commentary: 'Peak EP7 legislative output. Croatia joined EU (July 2013). MFF 2014-2020 negotiations concluded. Single Supervisory Mechanism adopted. Data protection reform debates intensified.' },
  { year: 2014, parliamentaryTerm: 'EP7/EP8 transition', mepCount: 751, plenarySessions: 47, legislativeActsAdopted: 78, rollCallVotes: 410, committeeMeetings: 1780, parliamentaryQuestions: 4120, resolutions: 115, speeches: 8000, adoptedTexts: 115, procedures: 838, events: 1901, documents: 3784, mepTurnover: 390, declarations: 580, commentary: 'EP7/EP8 transition. European elections May 2014—first with Spitzenkandidaten process. Jean-Claude Juncker elected Commission President. Reduced legislative output due to transition.' },
  { year: 2015, parliamentaryTerm: 'EP8 (2014-2019)', mepCount: 751, plenarySessions: 59, legislativeActsAdopted: 92, rollCallVotes: 510, committeeMeetings: 2150, parliamentaryQuestions: 5250, resolutions: 162, speeches: 11800, adoptedTexts: 476, procedures: 911, events: 1653, documents: 4597, mepTurnover: 45, declarations: 660, commentary: 'Migration crisis dominated agenda. Parliament established inquiry committee on Volkswagen emissions. Better Regulation agenda launched. TTIP negotiations controversial.' },
  { year: 2016, parliamentaryTerm: 'EP8 (2014-2019)', mepCount: 751, plenarySessions: 59, legislativeActsAdopted: 115, rollCallVotes: 570, committeeMeetings: 2340, parliamentaryQuestions: 5580, resolutions: 182, speeches: 13200, adoptedTexts: 513, procedures: 982, events: 1736, documents: 4665, mepTurnover: 38, declarations: 685, commentary: 'Brexit referendum (June 2016) reshaped EU political landscape. General Data Protection Regulation (GDPR) adopted. Panama Papers investigation. Increased scrutiny of Commission.' },
  { year: 2017, parliamentaryTerm: 'EP8 (2014-2019)', mepCount: 751, plenarySessions: 58, legislativeActsAdopted: 128, rollCallVotes: 600, committeeMeetings: 2420, parliamentaryQuestions: 5780, resolutions: 195, speeches: 13800, adoptedTexts: 503, procedures: 898, events: 1812, documents: 3962, mepTurnover: 42, declarations: 700, commentary: 'Article 50 negotiations began. Posting of Workers Directive revision. EU-Canada trade agreement (CETA) ratification. Strong legislative productivity as EP8 matured.' },
  { year: 2018, parliamentaryTerm: 'EP8 (2014-2019)', mepCount: 751, plenarySessions: 54, legislativeActsAdopted: 142, rollCallVotes: 650, committeeMeetings: 2550, parliamentaryQuestions: 6050, resolutions: 210, speeches: 14800, adoptedTexts: 367, procedures: 940, events: 1729, documents: 3927, mepTurnover: 35, declarations: 720, commentary: 'Peak EP8 legislative output. Copyright Directive heated debate. MFF 2021-2027 proposals. Clean Energy Package. Brexit Withdrawal Agreement negotiations. Highest roll-call vote count in EP8.' },
  { year: 2019, parliamentaryTerm: 'EP8/EP9 transition', mepCount: 751, plenarySessions: 52, legislativeActsAdopted: 65, rollCallVotes: 350, committeeMeetings: 1580, parliamentaryQuestions: 3680, resolutions: 98, speeches: 7000, adoptedTexts: 551, procedures: 749, events: 3103, documents: 3512, mepTurnover: 410, declarations: 540, commentary: 'EP8/EP9 transition. European elections May 2019. Fragmented parliament—no traditional two-party majority. Ursula von der Leyen narrowly elected Commission President. UK MEPs still present (Brexit delayed).' },
  { year: 2020, parliamentaryTerm: 'EP9 (2019-2024)', mepCount: 705, plenarySessions: 51, legislativeActsAdopted: 85, rollCallVotes: 460, committeeMeetings: 1950, parliamentaryQuestions: 5850, resolutions: 148, speeches: 9800, adoptedTexts: 390, procedures: 794, events: 3636, documents: 3250, mepTurnover: 95, declarations: 610, commentary: 'COVID-19 pandemic forced remote/hybrid plenary sessions. Brexit completed (UK MEPs departed January 2020, reducing count to 705). NextGenerationEU recovery fund negotiations. Unprecedented adaptation to digital parliament.' },
  { year: 2021, parliamentaryTerm: 'EP9 (2019-2024)', mepCount: 705, plenarySessions: 55, legislativeActsAdopted: 102, rollCallVotes: 530, committeeMeetings: 2180, parliamentaryQuestions: 6120, resolutions: 168, speeches: 11500, adoptedTexts: 517, procedures: 905, events: 4837, documents: 3820, mepTurnover: 48, declarations: 665, commentary: 'Continued hybrid working. Digital COVID Certificate legislation fast-tracked. Conference on the Future of Europe launched. Fit for 55 climate package proposals. MFF 2021-2027 operational. Questions spiked due to pandemic oversight.' },
  { year: 2022, parliamentaryTerm: 'EP9 (2019-2024)', mepCount: 705, plenarySessions: 58, legislativeActsAdopted: 120, rollCallVotes: 590, committeeMeetings: 2380, parliamentaryQuestions: 6350, resolutions: 192, speeches: 13500, adoptedTexts: 453, procedures: 843, events: 1097, documents: 4350, mepTurnover: 42, declarations: 695, commentary: 'Russia-Ukraine war dominated agenda. Energy crisis response. Digital Services Act and Digital Markets Act adopted. REPowerEU plan. Return to full in-person sessions. Parliament\'s foreign affairs role expanded significantly.' },
  { year: 2023, parliamentaryTerm: 'EP9 (2019-2024)', mepCount: 705, plenarySessions: 58, legislativeActsAdopted: 148, rollCallVotes: 660, committeeMeetings: 2520, parliamentaryQuestions: 6580, resolutions: 218, speeches: 15200, adoptedTexts: 487, procedures: 903, events: 1676, documents: 5020, mepTurnover: 38, declarations: 343, commentary: 'Peak EP9 legislative output. AI Act negotiations concluded. Nature Restoration Law controversial vote. Corporate Sustainability Due Diligence. Critical Raw Materials Act. Record-high legislative productivity driven by end-of-term urgency.' },
  { year: 2024, parliamentaryTerm: 'EP9/EP10 transition', mepCount: 720, plenarySessions: 50, legislativeActsAdopted: 72, rollCallVotes: 375, committeeMeetings: 1680, parliamentaryQuestions: 2970, resolutions: 108, speeches: 7800, adoptedTexts: 459, procedures: 676, events: 1378, documents: 2680, mepTurnover: 405, declarations: 3180, commentary: 'EP9/EP10 transition. European elections June 2024. Significant rightward shift in composition. New MEPs (720 total after redistribution). Reduced output due to election cycle. AI Act entered into force.' },
  { year: 2025, parliamentaryTerm: 'EP10 (2024-2029)', mepCount: 720, plenarySessions: 53, legislativeActsAdopted: 78, rollCallVotes: 420, committeeMeetings: 1980, parliamentaryQuestions: 4948, resolutions: 135, speeches: 10000, adoptedTexts: 347, procedures: 923, events: 2647, documents: 3516, mepTurnover: 36, declarations: 5145, commentary: 'EP10 ramp-up year (720 MEPs from 27 EU countries). New committee chairs and rapporteurs established. Defence and security policy gained prominence. Strategic autonomy debates. Clean Industrial Deal proposals. Parliament adapting to new political balance with stronger ECR and right-wing presence.' },
  { year: 2026, parliamentaryTerm: 'EP10 (2024-2029)', mepCount: 717, plenarySessions: 54, legislativeActsAdopted: 114, rollCallVotes: 567, committeeMeetings: 2363, parliamentaryQuestions: 6147, resolutions: 180, speeches: 997, adoptedTexts: 164, procedures: 935, events: 2327, documents: 4265, mepTurnover: 42, declarations: 2838, commentary: 'PARTIAL YEAR — data through Q1 2026. EP10 has 720 MEPs from 27 EU countries. Plenary session count (54) reflects the full-year EP calendar; speeches (996) and adoptedTexts (104) reflect actual Q1 cumulative activity; other activity totals are projected full-year estimates based on 2021-2025 historical average with EP10 year-2 cycle adjustment. Actual Q1 activity: 10 plenary sittings completed (Jan-Feb), adopted texts and procedures accumulating. Defence spending, Clean Industrial Deal, and AI Act implementation dominating legislative agenda.' },
];

const RAW_MONTHLY_DATA: Record<number, Record<string, number[]>> = {
  2026: {
    plenarySessions: [5, 5, 6, 4, 4, 4, 4, 0, 4, 8, 6, 4],
    speeches: [279, 314, 385, 19, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2025: {
    plenarySessions: [5, 4, 5, 3, 6, 4, 4, 0, 4, 8, 6, 4],
    events: [119, 158, 300, 262, 200, 235, 200, 5, 233, 362, 341, 232],
  },
  2024: {
    plenarySessions: [5, 8, 4, 6, 0, 0, 4, 0, 4, 8, 7, 4],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    events: [127, 175, 179, 121, 63, 37, 25, 4, 120, 175, 200, 152],
  },
  2023: {
    plenarySessions: [5, 7, 6, 4, 5, 5, 4, 0, 4, 8, 6, 4],
    events: [74, 79, 106, 91, 125, 133, 166, 14, 257, 219, 245, 167],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2022: {
    plenarySessions: [5, 4, 7, 4, 6, 6, 4, 0, 4, 8, 6, 4],
    events: [80, 74, 78, 64, 87, 90, 67, 0, 173, 169, 104, 111],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2021: {
    plenarySessions: [4, 4, 6, 4, 5, 6, 4, 0, 4, 8, 6, 4],
    events: [243, 281, 832, 836, 262, 350, 1282, 1, 459, 91, 98, 102],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2020: {
    plenarySessions: [6, 4, 3, 2, 4, 3, 4, 0, 4, 9, 7, 5],
    events: [424, 164, 132, 150, 422, 295, 285, 5, 546, 536, 331, 346],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2019: {
    plenarySessions: [6, 4, 8, 6, 0, 0, 7, 0, 4, 6, 6, 5],
    events: [179, 116, 505, 196, 37, 64, 250, 0, 295, 901, 278, 282],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2018: {
    plenarySessions: [4, 5, 5, 4, 6, 4, 4, 0, 4, 8, 6, 4],
    events: [106, 101, 119, 178, 160, 166, 173, 9, 198, 236, 165, 118],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2017: {
    plenarySessions: [4, 6, 6, 6, 5, 5, 4, 0, 4, 8, 6, 4],
    events: [89, 150, 148, 178, 120, 131, 128, 0, 352, 214, 169, 133],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2016: {
    plenarySessions: [4, 6, 4, 6, 6, 7, 4, 0, 4, 8, 5, 5],
    events: [112, 126, 91, 230, 135, 169, 101, 0, 231, 261, 140, 140],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2015: {
    plenarySessions: [5, 5, 5, 5, 5, 5, 4, 0, 6, 9, 5, 5],
    events: [121, 105, 147, 197, 104, 93, 105, 3, 203, 275, 152, 148],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2014: {
    plenarySessions: [4, 8, 4, 6, 0, 0, 7, 0, 4, 4, 6, 4],
    events: [119, 279, 211, 353, 90, 50, 131, 8, 171, 205, 153, 131],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2013: {
    events: [104, 55, 127, 152, 110, 174, 102, 12, 187, 236, 183, 240],
  },
  2012: {
    events: [89, 111, 156, 68, 139, 77, 102, 5, 206, 207, 138, 119],
  },
  2011: {
    events: [72, 103, 110, 76, 144, 131, 101, 2, 266, 181, 173, 191],
  },
  2010: {
    events: [42, 89, 104, 33, 171, 116, 94, 5, 230, 186, 160, 159],
  },
  2009: {
    events: [98, 95, 210, 199, 111, 61, 100, 17, 152, 238, 166, 111],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2008: {
    events: [108, 111, 180, 136, 112, 152, 130, 18, 213, 123, 131, 186],
    parliamentaryQuestions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  2007: {
    events: [78, 80, 88, 112, 83, 188, 125, 10, 192, 158, 156, 140],
  },
  2006: {
    events: [109, 119, 106, 130, 101, 127, 121, 14, 195, 131, 177, 269],
  },
  2005: {
    events: [99, 70, 64, 109, 108, 114, 117, 4, 167, 117, 124, 152],
  },
  2004: {
    events: [94, 125, 217, 187, 26, 6, 45, 15, 137, 101, 96, 140],
  },
};

const POLITICAL_LANDSCAPE: Record<number, PoliticalLandscapeData> = {
  2004: { groups: [{ name: 'EPP-ED', seats: 268, seatShare: 36.6 }, { name: 'PES', seats: 200, seatShare: 27.3 }, { name: 'ALDE', seats: 88, seatShare: 12.0 }, { name: 'Greens/EFA', seats: 42, seatShare: 5.7 }, { name: 'GUE/NGL', seats: 41, seatShare: 5.6 }, { name: 'IND/DEM', seats: 37, seatShare: 5.1 }, { name: 'UEN', seats: 27, seatShare: 3.7 }, { name: 'NI', seats: 29, seatShare: 4.0 }], totalGroups: 7, largestGroup: 'EPP-ED', largestGroupSeatShare: 36.6, fragmentationIndex: 4.12, grandCoalitionPossible: true, politicalBalance: 'Centre-right dominated with EPP-ED as largest group; centre-left PES as main opposition' },
  2005: { groups: [{ name: 'EPP-ED', seats: 268, seatShare: 36.6 }, { name: 'PES', seats: 200, seatShare: 27.3 }, { name: 'ALDE', seats: 88, seatShare: 12.0 }, { name: 'Greens/EFA', seats: 42, seatShare: 5.7 }, { name: 'GUE/NGL', seats: 41, seatShare: 5.6 }, { name: 'IND/DEM', seats: 37, seatShare: 5.1 }, { name: 'UEN', seats: 27, seatShare: 3.7 }, { name: 'NI', seats: 29, seatShare: 4.0 }], totalGroups: 7, largestGroup: 'EPP-ED', largestGroupSeatShare: 36.6, fragmentationIndex: 4.12, grandCoalitionPossible: true, politicalBalance: 'Stable EP6 configuration with EPP-ED/PES grand coalition governing most legislation' },
  2006: { groups: [{ name: 'EPP-ED', seats: 264, seatShare: 36.1 }, { name: 'PES', seats: 201, seatShare: 27.5 }, { name: 'ALDE', seats: 90, seatShare: 12.3 }, { name: 'Greens/EFA', seats: 42, seatShare: 5.7 }, { name: 'GUE/NGL', seats: 41, seatShare: 5.6 }, { name: 'IND/DEM', seats: 24, seatShare: 3.3 }, { name: 'UEN', seats: 30, seatShare: 4.1 }, { name: 'NI', seats: 40, seatShare: 5.5 }], totalGroups: 7, largestGroup: 'EPP-ED', largestGroupSeatShare: 36.1, fragmentationIndex: 4.22, grandCoalitionPossible: true, politicalBalance: 'EPP-ED/PES grand coalition continued; ALDE as kingmaker on contested files' },
  2007: { groups: [{ name: 'EPP-ED', seats: 288, seatShare: 36.7 }, { name: 'PES', seats: 215, seatShare: 27.4 }, { name: 'ALDE', seats: 100, seatShare: 12.7 }, { name: 'UEN', seats: 44, seatShare: 5.6 }, { name: 'Greens/EFA', seats: 43, seatShare: 5.5 }, { name: 'GUE/NGL', seats: 41, seatShare: 5.2 }, { name: 'IND/DEM', seats: 22, seatShare: 2.8 }, { name: 'NI', seats: 32, seatShare: 4.1 }], totalGroups: 7, largestGroup: 'EPP-ED', largestGroupSeatShare: 36.7, fragmentationIndex: 4.18, grandCoalitionPossible: true, politicalBalance: 'Post-enlargement: BG/RO MEPs distributed across groups; EPP-ED strengthened slightly' },
  2008: { groups: [{ name: 'EPP-ED', seats: 288, seatShare: 36.7 }, { name: 'PES', seats: 215, seatShare: 27.4 }, { name: 'ALDE', seats: 100, seatShare: 12.7 }, { name: 'UEN', seats: 44, seatShare: 5.6 }, { name: 'Greens/EFA', seats: 43, seatShare: 5.5 }, { name: 'GUE/NGL', seats: 41, seatShare: 5.2 }, { name: 'IND/DEM', seats: 22, seatShare: 2.8 }, { name: 'NI', seats: 32, seatShare: 4.1 }], totalGroups: 7, largestGroup: 'EPP-ED', largestGroupSeatShare: 36.7, fragmentationIndex: 4.18, grandCoalitionPossible: true, politicalBalance: 'Stable late-EP6 composition; financial crisis united mainstream groups on emergency measures' },
  2009: { groups: [{ name: 'EPP', seats: 265, seatShare: 36.0 }, { name: 'S&D', seats: 184, seatShare: 25.0 }, { name: 'ALDE', seats: 84, seatShare: 11.4 }, { name: 'Greens/EFA', seats: 55, seatShare: 7.5 }, { name: 'ECR', seats: 54, seatShare: 7.3 }, { name: 'GUE/NGL', seats: 35, seatShare: 4.8 }, { name: 'EFD', seats: 32, seatShare: 4.3 }, { name: 'NI', seats: 27, seatShare: 3.7 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 36.0, fragmentationIndex: 4.48, grandCoalitionPossible: true, politicalBalance: 'EP7 began: EPP renamed (dropped ED), S&D replaced PES. New ECR group formed by UK Conservatives. Increased fragmentation' },
  2010: { groups: [{ name: 'EPP', seats: 265, seatShare: 36.0 }, { name: 'S&D', seats: 184, seatShare: 25.0 }, { name: 'ALDE', seats: 84, seatShare: 11.4 }, { name: 'Greens/EFA', seats: 55, seatShare: 7.5 }, { name: 'ECR', seats: 54, seatShare: 7.3 }, { name: 'GUE/NGL', seats: 35, seatShare: 4.8 }, { name: 'EFD', seats: 32, seatShare: 4.3 }, { name: 'NI', seats: 27, seatShare: 3.7 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 36.0, fragmentationIndex: 4.48, grandCoalitionPossible: true, politicalBalance: 'Eurozone crisis strengthened EPP/S&D cooperation on economic governance' },
  2011: { groups: [{ name: 'EPP', seats: 271, seatShare: 35.9 }, { name: 'S&D', seats: 189, seatShare: 25.1 }, { name: 'ALDE', seats: 85, seatShare: 11.3 }, { name: 'Greens/EFA', seats: 58, seatShare: 7.7 }, { name: 'ECR', seats: 53, seatShare: 7.0 }, { name: 'GUE/NGL', seats: 35, seatShare: 4.6 }, { name: 'EFD', seats: 34, seatShare: 4.5 }, { name: 'NI', seats: 29, seatShare: 3.8 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 35.9, fragmentationIndex: 4.52, grandCoalitionPossible: true, politicalBalance: 'Minor shifts from national elections; economic crisis maintained grand coalition pattern' },
  2012: { groups: [{ name: 'EPP', seats: 270, seatShare: 35.8 }, { name: 'S&D', seats: 190, seatShare: 25.2 }, { name: 'ALDE', seats: 85, seatShare: 11.3 }, { name: 'Greens/EFA', seats: 58, seatShare: 7.7 }, { name: 'ECR', seats: 53, seatShare: 7.0 }, { name: 'GUE/NGL', seats: 35, seatShare: 4.6 }, { name: 'EFD', seats: 34, seatShare: 4.5 }, { name: 'NI', seats: 29, seatShare: 3.8 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 35.8, fragmentationIndex: 4.53, grandCoalitionPossible: true, politicalBalance: 'Fiscal compact debates saw strong EPP/S&D coordination; eurosceptic groups strengthening' },
  2013: { groups: [{ name: 'EPP', seats: 275, seatShare: 35.9 }, { name: 'S&D', seats: 194, seatShare: 25.3 }, { name: 'ALDE', seats: 83, seatShare: 10.8 }, { name: 'Greens/EFA', seats: 58, seatShare: 7.6 }, { name: 'ECR', seats: 57, seatShare: 7.4 }, { name: 'GUE/NGL', seats: 35, seatShare: 4.6 }, { name: 'EFD', seats: 31, seatShare: 4.0 }, { name: 'NI', seats: 33, seatShare: 4.3 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 35.9, fragmentationIndex: 4.51, grandCoalitionPossible: true, politicalBalance: 'Croatia accession added MEPs; rising euroscepticism ahead of 2014 elections' },
  2014: { groups: [{ name: 'EPP', seats: 221, seatShare: 29.4 }, { name: 'S&D', seats: 191, seatShare: 25.4 }, { name: 'ECR', seats: 70, seatShare: 9.3 }, { name: 'ALDE', seats: 67, seatShare: 8.9 }, { name: 'GUE/NGL', seats: 52, seatShare: 6.9 }, { name: 'Greens/EFA', seats: 50, seatShare: 6.7 }, { name: 'EFDD', seats: 48, seatShare: 6.4 }, { name: 'NI', seats: 52, seatShare: 6.9 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 29.4, fragmentationIndex: 5.28, grandCoalitionPossible: true, politicalBalance: 'EP8: Major fragmentation increase. EPP lost ground, eurosceptic EFDD surged. First Spitzenkandidaten process' },
  2015: { groups: [{ name: 'EPP', seats: 217, seatShare: 28.9 }, { name: 'S&D', seats: 190, seatShare: 25.3 }, { name: 'ECR', seats: 74, seatShare: 9.9 }, { name: 'ALDE', seats: 68, seatShare: 9.1 }, { name: 'GUE/NGL', seats: 52, seatShare: 6.9 }, { name: 'Greens/EFA', seats: 50, seatShare: 6.7 }, { name: 'EFDD', seats: 45, seatShare: 6.0 }, { name: 'ENF', seats: 39, seatShare: 5.2 }, { name: 'NI', seats: 16, seatShare: 2.1 }], totalGroups: 8, largestGroup: 'EPP', largestGroupSeatShare: 28.9, fragmentationIndex: 5.48, grandCoalitionPossible: true, politicalBalance: 'ENF (Europe of Nations and Freedom) formed—far-right gaining structure; migration crisis polarized debates' },
  2016: { groups: [{ name: 'EPP', seats: 216, seatShare: 28.8 }, { name: 'S&D', seats: 189, seatShare: 25.2 }, { name: 'ECR', seats: 74, seatShare: 9.9 }, { name: 'ALDE', seats: 69, seatShare: 9.2 }, { name: 'GUE/NGL', seats: 52, seatShare: 6.9 }, { name: 'Greens/EFA', seats: 50, seatShare: 6.7 }, { name: 'EFDD', seats: 44, seatShare: 5.9 }, { name: 'ENF', seats: 40, seatShare: 5.3 }, { name: 'NI', seats: 17, seatShare: 2.3 }], totalGroups: 8, largestGroup: 'EPP', largestGroupSeatShare: 28.8, fragmentationIndex: 5.52, grandCoalitionPossible: true, politicalBalance: 'Brexit referendum shock; EP united against UK departure; populist groups gained momentum' },
  2017: { groups: [{ name: 'EPP', seats: 217, seatShare: 28.9 }, { name: 'S&D', seats: 189, seatShare: 25.2 }, { name: 'ECR', seats: 73, seatShare: 9.7 }, { name: 'ALDE', seats: 68, seatShare: 9.1 }, { name: 'GUE/NGL', seats: 52, seatShare: 6.9 }, { name: 'Greens/EFA', seats: 51, seatShare: 6.8 }, { name: 'EFDD', seats: 42, seatShare: 5.6 }, { name: 'ENF', seats: 40, seatShare: 5.3 }, { name: 'NI', seats: 19, seatShare: 2.5 }], totalGroups: 8, largestGroup: 'EPP', largestGroupSeatShare: 28.9, fragmentationIndex: 5.49, grandCoalitionPossible: true, politicalBalance: 'Macron effect anticipated; mainstream parties cooperated on Article 50; eurosceptics faced internal divisions' },
  2018: { groups: [{ name: 'EPP', seats: 218, seatShare: 29.0 }, { name: 'S&D', seats: 187, seatShare: 24.9 }, { name: 'ECR', seats: 75, seatShare: 10.0 }, { name: 'ALDE', seats: 68, seatShare: 9.1 }, { name: 'GUE/NGL', seats: 52, seatShare: 6.9 }, { name: 'Greens/EFA', seats: 52, seatShare: 6.9 }, { name: 'EFDD', seats: 41, seatShare: 5.5 }, { name: 'ENF', seats: 37, seatShare: 4.9 }, { name: 'NI', seats: 21, seatShare: 2.8 }], totalGroups: 8, largestGroup: 'EPP', largestGroupSeatShare: 29.0, fragmentationIndex: 5.46, grandCoalitionPossible: true, politicalBalance: 'Pre-election jockeying; Copyright Directive showed cross-party divisions; green wave beginning' },
  2019: { groups: [{ name: 'EPP', seats: 182, seatShare: 24.2 }, { name: 'S&D', seats: 154, seatShare: 20.5 }, { name: 'RE', seats: 108, seatShare: 14.4 }, { name: 'Greens/EFA', seats: 74, seatShare: 9.9 }, { name: 'ID', seats: 73, seatShare: 9.7 }, { name: 'ECR', seats: 62, seatShare: 8.3 }, { name: 'GUE/NGL', seats: 41, seatShare: 5.5 }, { name: 'NI', seats: 57, seatShare: 7.6 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 24.2, fragmentationIndex: 6.40, grandCoalitionPossible: false, politicalBalance: 'EP9: Historic fragmentation. EPP+S&D lost majority for first time. Renew Europe (ex-ALDE) grew. ID (far-right) formed. Green surge. No two-party majority possible' },
  2020: { groups: [{ name: 'EPP', seats: 187, seatShare: 26.5 }, { name: 'S&D', seats: 147, seatShare: 20.9 }, { name: 'RE', seats: 98, seatShare: 13.9 }, { name: 'Greens/EFA', seats: 67, seatShare: 9.5 }, { name: 'ID', seats: 76, seatShare: 10.8 }, { name: 'ECR', seats: 61, seatShare: 8.7 }, { name: 'GUE/NGL', seats: 39, seatShare: 5.5 }, { name: 'NI', seats: 30, seatShare: 4.3 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 26.5, fragmentationIndex: 6.01, grandCoalitionPossible: false, politicalBalance: 'Post-Brexit: 73 UK MEPs departed. Parliament reduced to 705. EPP slightly strengthened proportionally. COVID united mainstream' },
  2021: { groups: [{ name: 'EPP', seats: 177, seatShare: 25.1 }, { name: 'S&D', seats: 145, seatShare: 20.6 }, { name: 'RE', seats: 98, seatShare: 13.9 }, { name: 'ID', seats: 76, seatShare: 10.8 }, { name: 'Greens/EFA', seats: 73, seatShare: 10.4 }, { name: 'ECR', seats: 63, seatShare: 8.9 }, { name: 'GUE/NGL', seats: 39, seatShare: 5.5 }, { name: 'NI', seats: 34, seatShare: 4.8 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 25.1, fragmentationIndex: 6.23, grandCoalitionPossible: false, politicalBalance: 'Conference on the Future of Europe created unusual cross-group cooperation; Green Deal legislation required broad coalitions' },
  2022: { groups: [{ name: 'EPP', seats: 177, seatShare: 25.1 }, { name: 'S&D', seats: 145, seatShare: 20.6 }, { name: 'RE', seats: 101, seatShare: 14.3 }, { name: 'ID', seats: 62, seatShare: 8.8 }, { name: 'Greens/EFA', seats: 72, seatShare: 10.2 }, { name: 'ECR', seats: 66, seatShare: 9.4 }, { name: 'GUE/NGL', seats: 38, seatShare: 5.4 }, { name: 'NI', seats: 44, seatShare: 6.2 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 25.1, fragmentationIndex: 6.26, grandCoalitionPossible: false, politicalBalance: 'Ukraine war united mainstream; ID weakened as some parties distanced from Russia; ECR gained from Fidesz joining' },
  2023: { groups: [{ name: 'EPP', seats: 177, seatShare: 25.1 }, { name: 'S&D', seats: 142, seatShare: 20.1 }, { name: 'RE', seats: 101, seatShare: 14.3 }, { name: 'Greens/EFA', seats: 72, seatShare: 10.2 }, { name: 'ECR', seats: 68, seatShare: 9.6 }, { name: 'ID', seats: 62, seatShare: 8.8 }, { name: 'GUE/NGL', seats: 37, seatShare: 5.2 }, { name: 'NI', seats: 46, seatShare: 6.5 }], totalGroups: 7, largestGroup: 'EPP', largestGroupSeatShare: 25.1, fragmentationIndex: 6.32, grandCoalitionPossible: false, politicalBalance: 'Nature Restoration Law showed EPP willing to break with S&D on Green Deal; rightward pressure intensified pre-election' },
  2024: { groups: [{ name: 'EPP', seats: 188, seatShare: 26.1 }, { name: 'S&D', seats: 136, seatShare: 18.9 }, { name: 'PfE', seats: 84, seatShare: 11.7 }, { name: 'ECR', seats: 78, seatShare: 10.8 }, { name: 'RE', seats: 77, seatShare: 10.7 }, { name: 'Greens/EFA', seats: 53, seatShare: 7.4 }, { name: 'GUE/NGL', seats: 46, seatShare: 6.4 }, { name: 'ESN', seats: 25, seatShare: 3.5 }, { name: 'NI', seats: 33, seatShare: 4.6 }], totalGroups: 8, largestGroup: 'EPP', largestGroupSeatShare: 26.1, fragmentationIndex: 6.51, grandCoalitionPossible: false, politicalBalance: 'EP10: Rightward shift. PfE (Patriots for Europe) replaced ID. ESN (Europe of Sovereign Nations) new far-right. ECR strengthened. Greens lost significantly' },
  2025: { groups: [{ name: 'EPP', seats: 185, seatShare: 25.7 }, { name: 'S&D', seats: 135, seatShare: 18.8 }, { name: 'PfE', seats: 84, seatShare: 11.7 }, { name: 'ECR', seats: 79, seatShare: 11.0 }, { name: 'RE', seats: 76, seatShare: 10.6 }, { name: 'Greens/EFA', seats: 53, seatShare: 7.4 }, { name: 'GUE/NGL', seats: 46, seatShare: 6.4 }, { name: 'ESN', seats: 28, seatShare: 3.9 }, { name: 'NI', seats: 31, seatShare: 4.3 }], totalGroups: 8, largestGroup: 'EPP', largestGroupSeatShare: 25.7, fragmentationIndex: 6.59, grandCoalitionPossible: false, politicalBalance: 'EP10 settled: 720 MEPs from 27 EU countries. EPP seeking flexible majorities with ECR on defence/migration; Green Deal pace slowing; defence spending consensus building' },
  2026: { groups: [{ name: 'EPP', seats: 185, seatShare: 25.7 }, { name: 'S&D', seats: 135, seatShare: 18.8 }, { name: 'PfE', seats: 84, seatShare: 11.7 }, { name: 'ECR', seats: 79, seatShare: 11.0 }, { name: 'RE', seats: 76, seatShare: 10.6 }, { name: 'Greens/EFA', seats: 53, seatShare: 7.4 }, { name: 'GUE/NGL', seats: 46, seatShare: 6.4 }, { name: 'ESN', seats: 28, seatShare: 3.9 }, { name: 'NI', seats: 31, seatShare: 4.3 }], totalGroups: 8, largestGroup: 'EPP', largestGroupSeatShare: 25.7, fragmentationIndex: 6.59, grandCoalitionPossible: false, politicalBalance: 'EP10 year 2: 720 MEPs from 27 EU countries. EPP-led flexible majorities on defence and competitiveness. ECR consolidating as third force. Clean Industrial Deal and European Defence Industrial Strategy key legislative priorities' },
};

const DEFAULT_POLITICAL_LANDSCAPE: PoliticalLandscapeData = {
  groups: [],
  totalGroups: 0,
  largestGroup: 'Unknown',
  largestGroupSeatShare: 0,
  fragmentationIndex: 0,
  grandCoalitionPossible: false,
  politicalBalance: 'Data unavailable',
};

/** Safe division: returns 0 when divisor is 0. */
function safeDivide(numerator: number, denominator: number): number {
  return denominator === 0 ? 0 : numerator / denominator;
}

/** Round to specified decimal places. */
function roundTo(value: number, decimals: number): number {
  const factor = 10 ** decimals;
  return Math.round(value * factor) / factor;
}

/**
 * Compute political bloc analysis from political group composition.
 *
 * Produces both the traditional 1D left-right bloc breakdown AND
 * a multi-dimensional Political Compass analysis (economic × social
 * axes + EU integration axis). Groups are classified using explicit
 * membership sets for 1D blocs and GROUP_COMPASS for multi-axis analysis.
 * NI members are excluded from bloc analysis.
 */

const LEFT_BLOC_GROUPS = new Set(['GUE/NGL', 'The Left', 'PES', 'S&D', 'Greens/EFA']);
const CENTRE_BLOC_GROUPS = new Set(['ALDE', 'RE']);
const HARD_EUROSCEPTIC_THRESHOLD = 2.0;

function computePoliticalBlocAnalysis(groups: PoliticalGroupSnapshot[]): PoliticalBlocAnalysis {
  let leftShare = 0;
  let centreShare = 0;
  let rightShare = 0;
  let euroscepticShare = 0;

  for (const group of groups) {
    if (group.name === 'NI') continue;
    const compass = GROUP_COMPASS[group.name];
    if (compass === undefined) continue;
    if (LEFT_BLOC_GROUPS.has(group.name)) {
      leftShare += group.seatShare;
    } else if (CENTRE_BLOC_GROUPS.has(group.name)) {
      centreShare += group.seatShare;
    } else {
      rightShare += group.seatShare;
    }
    if (compass.euIntegration < HARD_EUROSCEPTIC_THRESHOLD) {
      euroscepticShare += group.seatShare;
    }
  }

  const bipolarTotal = roundTo(rightShare, 1) + roundTo(leftShare, 1);
  const bipolarIndex = bipolarTotal === 0
    ? 0
    : roundTo((roundTo(rightShare, 1) - roundTo(leftShare, 1)) / bipolarTotal, 3);

  return {
    leftBlocShare: roundTo(leftShare, 1),
    centreBlocShare: roundTo(centreShare, 1),
    rightBlocShare: roundTo(rightShare, 1),
    euroscepticShare: roundTo(euroscepticShare, 1),
    bipolarIndex,
    politicalCompass: computePoliticalCompass(groups),
  };
}

/** Classified political group with compass position attached. */
interface ClassifiedGroup {
  name: string; seats: number; seatShare: number; compass: GroupCompassPosition;
}

/** Filter groups to those with known compass positions, excluding NI. */
function classifyGroups(groups: PoliticalGroupSnapshot[]): ClassifiedGroup[] {
  const result: ClassifiedGroup[] = [];
  for (const g of groups) {
    if (g.name === 'NI') continue;
    const compass = GROUP_COMPASS[g.name];
    if (compass !== undefined) {
      result.push({ name: g.name, seats: g.seats, seatShare: g.seatShare, compass });
    }
  }
  return result;
}

/** Compute quadrant seat share distribution from classified groups. */
function computeQuadrantDistribution(classified: ClassifiedGroup[]): QuadrantDistribution {
  let libLeft = 0;
  let libRight = 0;
  let authLeft = 0;
  let authRight = 0;
  for (const g of classified) {
    const isLeft = g.compass.economic < 5.0;
    const isLib = g.compass.social < 5.0;
    if (isLib && isLeft) libLeft += g.seatShare;
    else if (isLib) libRight += g.seatShare;
    else if (isLeft) authLeft += g.seatShare;
    else authRight += g.seatShare;
  }
  return {
    libertarianLeft: roundTo(libLeft, 1),
    libertarianRight: roundTo(libRight, 1),
    authoritarianLeft: roundTo(authLeft, 1),
    authoritarianRight: roundTo(authRight, 1),
  };
}

/**
 * Compute multi-dimensional Political Compass metrics from group composition.
 * Produces seat-share-weighted positions on economic, social, and EU axes,
 * quadrant distribution, polarisation indices, and dominant quadrant.
 */
function computePoliticalCompass(groups: PoliticalGroupSnapshot[]): PoliticalCompassAnalysis {
  const classified = classifyGroups(groups);

  const totalShare = classified.reduce((s, g) => s + g.seatShare, 0);
  if (totalShare === 0) {
    return {
      parliamentEconomicPosition: 5, parliamentSocialPosition: 5,
      parliamentEuPosition: 5,
      quadrantDistribution: { libertarianLeft: 0, libertarianRight: 0, authoritarianLeft: 0, authoritarianRight: 0 },
      dominantQuadrant: 'libertarianLeft', authLibTension: 0,
      economicPolarisation: 0, euIntegrationDispersion: 0,
    };
  }

  const wEcon = classified.reduce((s, g) => s + g.compass.economic * g.seatShare, 0) / totalShare;
  const wSocial = classified.reduce((s, g) => s + g.compass.social * g.seatShare, 0) / totalShare;
  const wEU = classified.reduce((s, g) => s + g.compass.euIntegration * g.seatShare, 0) / totalShare;

  const quadrantDistribution = computeQuadrantDistribution(classified);

  const quadrants: { key: PoliticalQuadrant; value: number }[] = [
    { key: 'libertarianLeft', value: quadrantDistribution.libertarianLeft },
    { key: 'libertarianRight', value: quadrantDistribution.libertarianRight },
    { key: 'authoritarianLeft', value: quadrantDistribution.authoritarianLeft },
    { key: 'authoritarianRight', value: quadrantDistribution.authoritarianRight },
  ];
  const dominantQuadrant = quadrants.reduce((best, q) =>
    q.value > best.value ? q : best
  ).key;

  const wVarEcon = classified.reduce((s, g) =>
    s + g.seatShare * (g.compass.economic - wEcon) ** 2, 0
  ) / totalShare;
  const wVarSocial = classified.reduce((s, g) =>
    s + g.seatShare * (g.compass.social - wSocial) ** 2, 0
  ) / totalShare;
  const wVarEU = classified.reduce((s, g) =>
    s + g.seatShare * (g.compass.euIntegration - wEU) ** 2, 0
  ) / totalShare;

  return {
    parliamentEconomicPosition: roundTo(wEcon, 2),
    parliamentSocialPosition: roundTo(wSocial, 2),
    parliamentEuPosition: roundTo(wEU, 2),
    quadrantDistribution,
    dominantQuadrant,
    authLibTension: roundTo(Math.sqrt(wVarSocial), 2),
    economicPolarisation: roundTo(Math.sqrt(wVarEcon), 2),
    euIntegrationDispersion: roundTo(Math.sqrt(wVarEU), 2),
  };
}

/** Raw annual data type before computed fields are added. */
type RawYearlyData = Omit<YearlyStats, 'monthlyActivity' | 'politicalLandscape' | 'derivedIntelligence'>;

/** Count the fewest groups needed to reach a majority (cumulative > 50%). */
function computeMinimumWinningCoalition(sorted: PoliticalGroupSnapshot[]): number {
  let cumulative = 0;
  let count = 0;
  for (const g of sorted) {
    if (g.name === 'NI') continue;
    cumulative += g.seatShare;
    count++;
    if (cumulative > 50) break;
  }
  return count;
}

/** Get seat share at a given rank position (0-indexed), defaulting to 0. */
function shareAtRank(sorted: PoliticalGroupSnapshot[], rank: number): number {
  return sorted[rank]?.seatShare ?? 0;
}

/** Compute political concentration metrics from group composition. */
function computeConcentrationMetrics(landscape: PoliticalLandscapeData): {
  topTwoGroupsConcentration: number; topThreeGroupsConcentration: number;
  herfindahlHirschmanIndex: number; dominanceRatio: number;
  majorityThresholdGap: number; minimumWinningCoalitionSize: number;
  grandCoalitionSurplusDeficit: number; nonAttachedShare: number;
  effectiveOppositionParties: number;
} {
  const groups = landscape.groups;
  const recognisedGroups = groups.filter((g) => g.name !== 'NI');
  const sortedRecognised = [...recognisedGroups].sort((a, b) => b.seatShare - a.seatShare);
  const top2 = shareAtRank(sortedRecognised, 0) + shareAtRank(sortedRecognised, 1);
  const hhi = roundTo(groups.reduce((s, g) => s + (g.seatShare / 100) ** 2, 0), 4);
  const ni = groups.find((g) => g.name === 'NI');
  return {
    topTwoGroupsConcentration: roundTo(top2, 1),
    topThreeGroupsConcentration: roundTo(top2 + shareAtRank(sortedRecognised, 2), 1),
    herfindahlHirschmanIndex: hhi,
    dominanceRatio: roundTo(
      safeDivide(landscape.largestGroupSeatShare, shareAtRank(sortedRecognised, 1)),
      2,
    ),
    majorityThresholdGap: roundTo(50 - landscape.largestGroupSeatShare, 1),
    minimumWinningCoalitionSize: computeMinimumWinningCoalition(sortedRecognised),
    grandCoalitionSurplusDeficit: roundTo(top2 - 50, 1),
    nonAttachedShare: ni?.seatShare ?? 0,
    effectiveOppositionParties: roundTo(landscape.fragmentationIndex - 1, 2),
  };
}

/** Classify institutional memory risk based on MEP turnover rate. */
function classifyMemoryRisk(turnoverRate: number): 'HIGH' | 'MEDIUM' | 'LOW' {
  if (turnoverRate > 40) return 'HIGH';
  if (turnoverRate > 20) return 'MEDIUM';
  return 'LOW';
}

/** Compute year-over-year dynamics (returns nulls for first year). */
function computeYoYDynamics(
  y: RawYearlyData,
  landscape: PoliticalLandscapeData,
  prevYear: RawYearlyData | null,
  prevLandscape: PoliticalLandscapeData | null,
): { legislativeOutputChange: number | null; fragmentationVelocity: number | null; questionsChange: number | null } {
  if (prevYear === null || prevLandscape === null) {
    return { legislativeOutputChange: null, fragmentationVelocity: null, questionsChange: null };
  }
  return {
    legislativeOutputChange: roundTo(
      safeDivide(y.legislativeActsAdopted - prevYear.legislativeActsAdopted, prevYear.legislativeActsAdopted) * 100, 1,
    ),
    fragmentationVelocity: roundTo(landscape.fragmentationIndex - prevLandscape.fragmentationIndex, 2),
    questionsChange: roundTo(
      safeDivide(y.parliamentaryQuestions - prevYear.parliamentaryQuestions, prevYear.parliamentaryQuestions) * 100, 1,
    ),
  };
}

/**
 * Compute all derived intelligence metrics for a single year.
 *
 * @param y - Raw annual activity data
 * @param landscape - Political landscape data for the year
 * @param prevYear - Previous year's data (null for the first year in the series)
 * @param prevLandscape - Previous year's political landscape (null for the first year)
 */
function computeDerivedIntelligence(
  y: RawYearlyData,
  landscape: PoliticalLandscapeData,
  prevYear: RawYearlyData | null,
  prevLandscape: PoliticalLandscapeData | null,
): DerivedIntelligenceMetrics {
  const turnoverRate = roundTo(safeDivide(y.mepTurnover, y.mepCount) * 100, 1);
  const concentration = computeConcentrationMetrics(landscape);
  const yoy = computeYoYDynamics(y, landscape, prevYear, prevLandscape);

  return {
    legislativeOutputPerSession: roundTo(safeDivide(y.legislativeActsAdopted, y.plenarySessions), 2),
    legislativeOutputPerMEP: roundTo(safeDivide(y.legislativeActsAdopted, y.mepCount), 3),
    rollCallVoteYield: roundTo(safeDivide(y.legislativeActsAdopted, y.rollCallVotes) * 100, 1),
    procedureCompletionRate: roundTo(safeDivide(y.legislativeActsAdopted, y.procedures) * 100, 1),
    resolutionToLegislationRatio: roundTo(safeDivide(y.resolutions, y.legislativeActsAdopted), 2),
    documentBurdenPerAct: roundTo(safeDivide(y.documents, y.legislativeActsAdopted), 1),
    mepOversightIntensity: roundTo(safeDivide(y.parliamentaryQuestions, y.mepCount), 2),
    mepSpeechRate: roundTo(safeDivide(y.speeches, y.mepCount), 1),
    debateIntensityPerSession: roundTo(safeDivide(y.speeches, y.plenarySessions), 1),
    oversightPerSession: roundTo(safeDivide(y.parliamentaryQuestions, y.plenarySessions), 1),
    ...concentration,
    politicalBlocAnalysis: computePoliticalBlocAnalysis(landscape.groups),
    mepStabilityIndex: roundTo(1 - safeDivide(y.mepTurnover, y.mepCount), 3),
    turnoverRate,
    institutionalMemoryRisk: classifyMemoryRisk(turnoverRate),
    declarationCoverageRatio: roundTo(safeDivide(y.declarations, y.mepCount), 2),
    legislativeOutputChange: yoy.legislativeOutputChange,
    fragmentationVelocity: yoy.fragmentationVelocity,
    questionsChange: yoy.questionsChange,
    oversightToLegislationBalance: roundTo(safeDivide(y.parliamentaryQuestions, y.legislativeActsAdopted), 1),
    speechToVoteRatio: roundTo(safeDivide(y.speeches, y.rollCallVotes), 1),
    committeeToPlenaryRatio: roundTo(safeDivide(y.committeeMeetings, y.plenarySessions), 1),
  };
}

function buildYearlyStats(): YearlyStats[] {
  return RAW_YEARLY.map((y, idx) => {
    const landscape = POLITICAL_LANDSCAPE[y.year] ?? DEFAULT_POLITICAL_LANDSCAPE;
    const prevRaw = idx > 0 ? (RAW_YEARLY[idx - 1] ?? null) : null;
    const prevLandscape = prevRaw !== null
      ? (POLITICAL_LANDSCAPE[prevRaw.year] ?? null)
      : null;
    return {
      ...y,
      monthlyActivity: distributeMonthly(y),
      politicalLandscape: landscape,
      derivedIntelligence: computeDerivedIntelligence(y, landscape, prevRaw, prevLandscape),
    };
  });
}

function computeRankings(yearly: YearlyStats[]): CategoryRanking[] {
  const categories: { key: keyof YearlyStats; label: string }[] = [
    { key: 'plenarySessions', label: 'Plenary Sessions' },
    { key: 'legislativeActsAdopted', label: 'Legislative Acts Adopted' },
    { key: 'rollCallVotes', label: 'Roll-Call Votes' },
    { key: 'committeeMeetings', label: 'Committee Meetings' },
    { key: 'parliamentaryQuestions', label: 'Parliamentary Questions' },
    { key: 'resolutions', label: 'Resolutions' },
    { key: 'speeches', label: 'Speeches' },
    { key: 'adoptedTexts', label: 'Adopted Texts' },
    { key: 'procedures', label: 'Procedures' },
    { key: 'events', label: 'Events' },
    { key: 'documents', label: 'Documents' },
    { key: 'mepTurnover', label: 'MEP Turnover' },
    { key: 'declarations', label: 'Declarations' },
  ];

  return categories.map(({ key, label }) => {
    const values = yearly.map((y) => ({
      year: y.year,
      value: y[key] as number,
    }));
    const sorted = [...values].sort((a, b) => b.value - a.value);
    const n = sorted.length;

    const numericValues = values.map((v) => v.value);
    const mean = numericValues.reduce((s, v) => s + v, 0) / n;
    const variance = numericValues.reduce((s, v) => s + (v - mean) ** 2, 0) / n;
    const stdDev = Math.round(Math.sqrt(variance) * 100) / 100;
    const sortedValues = [...numericValues].sort((a, b) => a - b);
    const median = n % 2 === 0
      ? ((sortedValues[n / 2 - 1] ?? 0) + (sortedValues[n / 2] ?? 0)) / 2
      : sortedValues[Math.floor(n / 2)] ?? 0;

    const rankings: RankedYear[] = sorted.map((entry, idx) => ({
      year: entry.year,
      rank: idx + 1,
      percentile: Math.round(((n - idx - 1) / (n - 1)) * 10000) / 100,
      totalActivityScore: entry.value,
    }));

    return {
      category: label,
      rankings,
      mean: Math.round(mean * 100) / 100,
      stdDev,
      median,
      topYear: sorted[0]?.year ?? 0,
      bottomYear: sorted[n - 1]?.year ?? 0,
    };
  });
}

function buildPredictions(): PredictionYear[] {
  const trendYears = RAW_YEARLY.filter((y) =>
    [2021, 2022, 2023, 2024, 2025].includes(y.year)
  );

  const avg = (fn: (y: typeof trendYears[number]) => number): number =>
    Math.round(trendYears.reduce((s, y) => s + fn(y), 0) / trendYears.length);

  const avgSessions = avg((y) => y.plenarySessions);
  const avgActs = avg((y) => y.legislativeActsAdopted);
  const avgVotes = avg((y) => y.rollCallVotes);
  const avgCommittees = avg((y) => y.committeeMeetings);
  const avgQuestions = avg((y) => y.parliamentaryQuestions);
  const avgResolutions = avg((y) => y.resolutions);
  const avgSpeeches = avg((y) => y.speeches);
  const avgAdoptedTexts = avg((y) => y.adoptedTexts);
  const avgProcedures = avg((y) => y.procedures);
  const avgEvents = avg((y) => y.events);
  const avgDocuments = avg((y) => y.documents);
  const avgMepTurnover = avg((y) => y.mepTurnover);
  const avgDeclarations = avg((y) => y.declarations);

  const termCurve = [
    { year: 2027, factor: 1.15, conf: '±12%', note: 'EP10 year 3 — peak legislative productivity expected' },
    { year: 2028, factor: 1.20, conf: '±15%', note: 'EP10 year 4 — highest output before end-of-term push' },
    { year: 2029, factor: 0.75, conf: '±18%', note: 'EP10 year 5 — election transition, reduced output' },
    { year: 2030, factor: 0.90, conf: '±22%', note: 'EP11 year 1 — new term establishment phase' },
    { year: 2031, factor: 1.10, conf: '±25%', note: 'EP11 year 2 — ramp-up, committees fully operational' },
  ];

  return termCurve.map(({ year, factor, conf, note }) => ({
    year,
    predictedPlenarySessions: Math.round(avgSessions * factor),
    predictedLegislativeActs: Math.round(avgActs * factor),
    predictedRollCallVotes: Math.round(avgVotes * factor),
    predictedCommitteeMeetings: Math.round(avgCommittees * factor),
    predictedParliamentaryQuestions: Math.round(avgQuestions * factor),
    predictedResolutions: Math.round(avgResolutions * factor),
    predictedSpeeches: Math.round(avgSpeeches * factor),
    predictedAdoptedTexts: Math.round(avgAdoptedTexts * factor),
    predictedProcedures: Math.round(avgProcedures * factor),
    predictedEvents: Math.round(avgEvents * factor),
    predictedDocuments: Math.round(avgDocuments * factor),
    predictedMepTurnover: Math.round(avgMepTurnover * factor),
    predictedDeclarations: Math.round(avgDeclarations * factor),
    confidenceInterval: conf,
    methodology: `Average-based extrapolation from 2021-2025 with parliamentary term cycle adjustment (factor: ${String(factor)}). ${note}`,
  }));
}

/**
 * Find the largest year-over-year increase in eurosceptic share.
 * Returns the start/end year of the largest surge, or null if none.
 */
function findLargestEuroscepticSurge(
  yearly: YearlyStats[],
): { startYear: number; endYear: number } | null {
  let maxSurge = 0;
  let surgeStartYear = 0;
  let surgeEndYear = 0;
  for (let i = 1; i < yearly.length; i++) {
    const prev = yearly[i - 1];
    const curr = yearly[i];
    if (prev && curr) {
      const delta =
        curr.derivedIntelligence.politicalBlocAnalysis.euroscepticShare -
        prev.derivedIntelligence.politicalBlocAnalysis.euroscepticShare;
      if (delta > maxSurge) {
        maxSurge = delta;
        surgeStartYear = prev.year;
        surgeEndYear = curr.year;
      }
    }
  }
  return maxSurge > 0 ? { startYear: surgeStartYear, endYear: surgeEndYear } : null;
}

/**
 * Build additional key findings from the derived intelligence metrics.
 * These findings are based on OSINT-derived political concentration,
 * legislative efficiency, and institutional stability metrics.
 */
function buildDerivedKeyFindings(yearly: YearlyStats[]): string[] {
  const findings: string[] = [];

  const first = yearly[0];
  const last = yearly[yearly.length - 1];
  if (first && last) {
    const firstDI = first.derivedIntelligence;
    const lastDI = last.derivedIntelligence;

    const cr2ThresholdCrossingYear = yearly.find(
      (y) => y.derivedIntelligence.topTwoGroupsConcentration < 50,
    )?.year;
    const cr2ThresholdText = cr2ThresholdCrossingYear !== undefined
      ? `, crossing the 50% majority threshold in ${String(cr2ThresholdCrossingYear)}`
      : '';
    findings.push(
      `OSINT: Top-2 group concentration (CR₂) fell from ${String(firstDI.topTwoGroupsConcentration)}% (${String(first.year)}) to ${String(lastDI.topTwoGroupsConcentration)}% (${String(last.year)})${cr2ThresholdText}—a structural regime change requiring 3+ groups for every legislative majority.`,
    );

    findings.push(
      `OSINT: Minimum winning coalition size increased from ${String(firstDI.minimumWinningCoalitionSize)} groups (${String(first.year)}) to ${String(lastDI.minimumWinningCoalitionSize)} groups (${String(last.year)}), increasing legislative negotiation complexity.`,
    );

    findings.push(
      `OSINT: MEP oversight intensity rose from ${String(firstDI.mepOversightIntensity)} to ${String(lastDI.mepOversightIntensity)} questions per MEP, indicating structurally stronger Commission scrutiny.`,
    );

    findings.push(
      `OSINT: Bipolar index shifted from ${String(firstDI.politicalBlocAnalysis.bipolarIndex)} (${String(first.year)}) to ${String(lastDI.politicalBlocAnalysis.bipolarIndex)} (${String(last.year)}), reflecting a ${lastDI.politicalBlocAnalysis.bipolarIndex > firstDI.politicalBlocAnalysis.bipolarIndex ? 'rightward' : 'leftward'} political rebalancing.`,
    );

    const surge = findLargestEuroscepticSurge(yearly);
    const surgeText = surge !== null
      ? `, with the most significant surge in ${String(surge.startYear)}-${String(surge.endYear)}`
      : '';
    findings.push(
      `OSINT: Eurosceptic/far-right seat share grew from ${String(firstDI.politicalBlocAnalysis.euroscepticShare)}% (${String(first.year)}) to ${String(lastDI.politicalBlocAnalysis.euroscepticShare)}% (${String(last.year)})${surgeText}.`,
    );

    findings.push(
      `OSINT: Herfindahl-Hirschman Index fell from ${String(firstDI.herfindahlHirschmanIndex)} to ${String(lastDI.herfindahlHirschmanIndex)}, confirming deconcentration from a near-duopoly to a multi-polar party system.`,
    );
  }

  return findings;
}

function buildAnalysisSummary(yearly: YearlyStats[]): GeneratedStatsData['analysisSummary'] {
  const actsPerYear = yearly.map((y) => y.legislativeActsAdopted);
  const avgActs = Math.round(actsPerYear.reduce((s, v) => s + v, 0) / actsPerYear.length);
  const peakYear = yearly.reduce((best, y) =>
    y.legislativeActsAdopted > best.legislativeActsAdopted ? y : best
  );
  const lowestYear = yearly.reduce((worst, y) =>
    y.legislativeActsAdopted < worst.legislativeActsAdopted ? y : worst
  );

  const recentAvg = yearly.slice(-5).reduce((s, y) => s + y.legislativeActsAdopted, 0) / 5;
  const olderAvg = yearly.slice(0, 5).reduce((s, y) => s + y.legislativeActsAdopted, 0) / 5;
  let trend: string;
  if (recentAvg > olderAvg * 1.1) {
    trend = 'INCREASING';
  } else if (recentAvg < olderAvg * 0.9) {
    trend = 'DECREASING';
  } else {
    trend = 'STABLE';
  }

  return {
    overallTrend: `Legislative productivity shows a ${trend.toLowerCase()} trend over the 2004-2026 period. Each parliamentary term follows a characteristic bell curve with peak activity in years 3-4 and reduced output in election transition years.`,
    peakActivityYear: peakYear.year,
    lowestActivityYear: lowestYear.year,
    averageAnnualLegislativeOutput: avgActs,
    legislativeProductivityTrend: trend,
    keyFindings: [
      'Election transition years (2009, 2014, 2019, 2024) consistently show 30-40% reduced legislative output compared to mid-term peaks.',
      'The Lisbon Treaty (2009) structurally increased Parliament\'s legislative role, resulting in higher baseline activity from EP7 onwards.',
      'COVID-19 (2020) caused a temporary dip but Parliament adapted quickly to hybrid working, with 2021-2023 showing strong recovery.',
      'Parliamentary questions have trended upward, reflecting increased MEP engagement in Commission oversight.',
      'EP9 (2019-2024) achieved the highest peak legislative output (148 acts in 2023), driven by digital regulation and Green Deal.',
      'EP10 shows a rightward political shift with implications for legislative priorities in defence, migration, and industrial policy.',
      'Committee meeting frequency has increased 30% from EP6 to EP9, reflecting growing legislative complexity.',
      'Roll-call vote counts correlate strongly (r=0.94) with legislative acts adopted, indicating consistent parliamentary discipline.',
      'Parliamentary fragmentation has steadily increased: Effective Number of Parties rose from 4.12 (2004) to 6.59 (2026), reflecting the decline of the traditional EPP-S&D grand coalition.',
      'Since 2019 (EP9), no two-party majority has been possible, requiring broader multi-group coalitions for legislation.',
      'Speech counts track legislative intensity, peaking during end-of-term legislative pushes (2013, 2018, 2023).',
      ...buildDerivedKeyFindings(yearly),
    ],
  };
}

const yearlyStats = buildYearlyStats();
const categoryRankings = computeRankings(yearlyStats);
const predictions = buildPredictions();
const analysisSummary = buildAnalysisSummary(yearlyStats);

/**
 * Precomputed European Parliament activity dataset (2004-2026) used by
 * the `get_all_generated_stats` MCP tool.
 *
 * Includes monthly breakdowns and yearly totals for plenary sessions,
 * legislative acts, roll-call votes, committee meetings, parliamentary
 * questions, resolutions, speeches, adopted texts, procedures, events,
 * documents, MEP turnover and declarations, plus per-year
 * {@link PoliticalLandscapeData} snapshots.
 *
 * Data is refreshed weekly by an agentic workflow; see
 * `src/tools/getAllGeneratedStats.ts` for retrieval and filtering logic.
 */
export const GENERATED_STATS: GeneratedStatsData = {
  generatedAt: '2026-05-18T07:24:18Z',
  coveragePeriod: { from: 2004, to: 2026 },
  methodologyVersion: '2.0.0',
  dataSource: 'European Parliament Open Data Portal — data.europarl.europa.eu',
  yearlyStats,
  categoryRankings,
  predictions,
  analysisSummary,
};
