All files / src/utils intelligence-analysis.ts

97.08% Statements 366/377
91.4% Branches 266/291
100% Functions 62/62
98.67% Lines 298/302

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045                                                                                10x     10x     10x     10x                               253x                     117x                   32x 46x                   67x 52x                       10x 10x                   20x 20x                   13x 13x                           16x 16x 11x 16x 10x                                       16x 16x 14x 16x 13x                                     10x 10x 8x 10x 10x 6x                                       11x 11x 9x 11x 11x 7x                                                   7x 12x 12x 12x 5x 12x 12x                                     7x 6x 6x 8x 6x                                 936x 515x 75x                                 156x 936x 936x 936x                                             14x 14x 10x 10x 9x 9x 9x 9x     14x 14x 14x     14x                                               156x   936x   936x 936x     156x                             4x         4x           4x   5x 5x 1x 1x           7x                             62x   52x 52x 52x 52x 52x   52x 52x 52x 73x 73x 71x   71x 71x 71x 71x     71x 71x     71x 71x 70x 70x 70x   70x 70x 70x       52x   51x                                               6x 6x 6x     6x 6x 7x 7x 7x     7x 6x 3x     7x 4x 4x 3x   7x                     6x 6x 3x 3x                       51x 51x 51x 92x 92x   51x                   51x 92x 51x 51x 51x 92x 92x   51x                   51x 19x 2x 2x                           59x   51x 51x   51x 51x   51x                                   33x                                   11x 11x   11x 36x 36x       35x 35x 35x 35x     35x 35x   33x 33x 33x 28x 5x 5x           11x                   66x 66x 33x                     11x 11x 10x 7x                               11x 11x 9x 9x                                                 15x 18x 11x 11x 3x 3x                                             13x   11x 60x 60x   11x 30x 30x 30x 28x     11x 11x   11x 11x 11x   11x   11x 11x   11x 11x   11x 11x 33x 11x 11x 11x 11x 11x                   12x                           9x 1x                   8x 8x 8x 21x 21x 19x 19x 19x 19x 19x 4x   15x       8x 8x 8x 8x   8x 19x 15x 15x   15x 7x 8x 5x         8x     9x 4x 2x   8x                                                 11x   10x       11x 24x 24x       11x 8x     6x 17x 17x 17x 17x           6x 11x                   9x 15x 9x 9x 15x   9x                       9x 6x 6x 6x 10x 10x 10x   6x 6x                             10x 6x 2x 1x                           10x 1x                 9x 9x 21x 21x 21x   21x     21x     9x   9x 21x 21x   9x 9x   9x                
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Utils/IntelligenceAnalysis
 * @description Pure intelligence analysis utility functions for structured
 * assessment of European Parliament data. All functions are stateless and
 * safely handle malformed or missing MCP data. No side effects.
 */
 
import { escapeHTML } from './file-utils.js';
import type {
  VotingAnomalyIntelligence,
  CoalitionIntelligence,
  MEPInfluenceScore,
  LegislativeVelocity,
  StakeholderPerspective,
  StakeholderOutcomeMatrix,
  AnalysisStakeholderType,
  VotingRecord,
  VotingPattern,
  VotingIntensity,
  CoalitionShift,
  PolarizationIndex,
  VotingTrend,
  CoalitionStabilityReport,
  LegislativeVelocityReport,
  LegislativeDocument,
} from '../types/index.js';
import { ALL_STAKEHOLDER_TYPES } from '../types/index.js';
 
// ─── Internal type aliases ────────────────────────────────────────────────────
 
type SignificanceLevel = VotingAnomalyIntelligence['significance'];
type RiskLevel = CoalitionIntelligence['riskLevel'];
type AlignmentTrend = CoalitionIntelligence['alignmentTrend'];
 
// ─── Validation constants ─────────────────────────────────────────────────────
 
/** Valid significance levels in descending priority order */
const SIGNIFICANCE_LEVELS: readonly string[] = ['critical', 'high', 'medium', 'low'];
 
/** Valid risk levels for coalition and bottleneck assessment */
const RISK_LEVELS: readonly string[] = ['high', 'medium', 'low'];
 
/** Valid alignment trend values */
const ALIGNMENT_TRENDS: readonly string[] = ['strengthening', 'weakening', 'stable'];
 
/** Priority weights for significance-based ranking */
const SIGNIFICANCE_WEIGHTS: Readonly<Record<string, number>> = {
  critical: 4,
  high: 3,
  medium: 2,
  low: 1,
};
 
// ─── Private value-extraction helpers ────────────────────────────────────────
 
/**
 * Safely extract a string from an unknown field value
 *
 * @param val - Unknown value to coerce
 * @returns The string value or empty string if not a string
 */
function asStr(val: unknown): string {
  return typeof val === 'string' ? val : '';
}
 
/**
 * Safely extract a finite number from an unknown field value
 *
 * @param val - Unknown value to coerce
 * @param fallback - Value returned when input is not a finite number
 * @returns Finite number or fallback
 */
function asNum(val: unknown, fallback = 0): number {
  return typeof val === 'number' && Number.isFinite(val) ? val : fallback;
}
 
/**
 * Safely extract an array of strings from an unknown field value
 *
 * @param val - Unknown value to coerce
 * @returns Array of strings (empty array if input is not an array)
 */
function asStrArr(val: unknown): string[] {
  if (!Array.isArray(val)) return [];
  return (val as unknown[]).filter((v): v is string => typeof v === 'string');
}
 
/**
 * Coerce an unknown value to a non-null Record or return null
 *
 * @param input - Value to cast
 * @returns Record or null for null/undefined/non-object input
 */
function toRecord(input: unknown): Record<string, unknown> | null {
  if (input === null || input === undefined || typeof input !== 'object') return null;
  return input as Record<string, unknown>;
}
 
// ─── Private parsing validators ───────────────────────────────────────────────
 
/**
 * Validate and normalise a raw significance level string
 *
 * @param raw - Raw string from MCP data
 * @returns Validated SignificanceLevel, defaulting to 'low'
 */
function parseSignificance(raw: string): SignificanceLevel {
  const lower = raw.toLowerCase();
  return SIGNIFICANCE_LEVELS.includes(lower) ? (lower as SignificanceLevel) : 'low';
}
 
/**
 * Validate and normalise a raw risk level string
 *
 * @param raw - Raw string from MCP data
 * @returns Validated RiskLevel, defaulting to 'medium'
 */
function parseRiskLevel(raw: string): RiskLevel {
  const lower = raw.toLowerCase();
  return RISK_LEVELS.includes(lower) ? (lower as RiskLevel) : 'medium';
}
 
/**
 * Validate and normalise a raw alignment trend string
 *
 * @param raw - Raw string from MCP data
 * @returns Validated AlignmentTrend, defaulting to 'stable'
 */
function parseAlignmentTrend(raw: string): AlignmentTrend {
  const lower = raw.toLowerCase();
  return ALIGNMENT_TRENDS.includes(lower) ? (lower as AlignmentTrend) : 'stable';
}
 
// ─── Exported intelligence functions ─────────────────────────────────────────
 
/**
 * Parse and score a voting anomaly from raw MCP data.
 * Returns null for null, undefined, non-object, or inputs missing a valid
 * anomaly identifier.
 *
 * @param rawAnomaly - Raw MCP anomaly data (unknown shape)
 * @returns Structured VotingAnomalyIntelligence or null if input is invalid
 */
export function scoreVotingAnomaly(rawAnomaly: unknown): VotingAnomalyIntelligence | null {
  const a = toRecord(rawAnomaly);
  if (!a) return null;
  const anomalyId = asStr(a['anomalyId']) || asStr(a['id']);
  if (!anomalyId) return null;
  return {
    anomalyId,
    significance: parseSignificance(asStr(a['significance'])),
    description: asStr(a['description']),
    affectedGroups: asStrArr(a['affectedGroups']),
    deviationPercentage: asNum(a['deviationPercentage']),
    historicalContext: asStr(a['historicalContext']),
    implication: asStr(a['implication']),
  };
}
 
/**
 * Analyse a coalition's cohesion from raw MCP coalition data.
 * Returns null for null, undefined, non-object, or inputs missing a valid
 * coalition identifier.
 *
 * @param rawCoalition - Raw MCP coalition data (unknown shape)
 * @returns Structured CoalitionIntelligence or null if input is invalid
 */
export function analyzeCoalitionCohesion(rawCoalition: unknown): CoalitionIntelligence | null {
  const c = toRecord(rawCoalition);
  if (!c) return null;
  const coalitionId = asStr(c['coalitionId']) || asStr(c['id']);
  if (!coalitionId) return null;
  return {
    coalitionId,
    groups: asStrArr(c['groups']),
    cohesionScore: Math.min(1, Math.max(0, asNum(c['cohesionScore']))),
    alignmentTrend: parseAlignmentTrend(asStr(c['alignmentTrend'])),
    keyVotes: Math.max(0, Math.round(asNum(c['keyVotes']))),
    riskLevel: parseRiskLevel(asStr(c['riskLevel'])),
  };
}
 
/**
 * Extract and score MEP influence from raw MCP influence data.
 * Returns null for null, undefined, non-object, or inputs missing both a
 * valid MEP identifier and display name.
 *
 * @param rawInfluence - Raw MCP MEP influence data (unknown shape)
 * @returns Structured MEPInfluenceScore or null if input is invalid
 */
export function scoreMEPInfluence(rawInfluence: unknown): MEPInfluenceScore | null {
  const m = toRecord(rawInfluence);
  if (!m) return null;
  const mepId = asStr(m['mepId']) || asStr(m['id']);
  const mepName = asStr(m['mepName']) || asStr(m['name']);
  if (!mepId || !mepName) return null;
  return {
    mepId,
    mepName,
    overallScore: Math.min(100, Math.max(0, asNum(m['overallScore']))),
    votingActivity: Math.min(100, Math.max(0, asNum(m['votingActivity']))),
    legislativeOutput: Math.min(100, Math.max(0, asNum(m['legislativeOutput']))),
    committeeEngagement: Math.min(100, Math.max(0, asNum(m['committeeEngagement']))),
    rank: asStr(m['rank']),
  };
}
 
/**
 * Calculate legislative velocity from raw MCP procedure data.
 * Returns null for null, undefined, non-object, or inputs missing a valid
 * procedure identifier or title.
 *
 * @param rawProcedure - Raw MCP procedure data (unknown shape)
 * @returns Structured LegislativeVelocity or null if input is invalid
 */
export function calculateLegislativeVelocity(rawProcedure: unknown): LegislativeVelocity | null {
  const p = toRecord(rawProcedure);
  if (!p) return null;
  const procedureId = asStr(p['procedureId']) || asStr(p['id']);
  const title = asStr(p['title']);
  if (!procedureId || !title) return null;
  return {
    procedureId,
    title,
    stage: asStr(p['stage']) || 'Unknown',
    daysInCurrentStage: Math.max(0, Math.round(asNum(p['daysInCurrentStage']))),
    velocityScore: Math.min(1, Math.max(0, asNum(p['velocityScore']))),
    bottleneckRisk: parseRiskLevel(asStr(p['bottleneckRisk'])),
    predictedCompletion: asStr(p['predictedCompletion']),
  };
}
 
/**
 * Sort items by significance level descending, with numeric score as
 * tie-breaker. Items with higher significance or scores appear first.
 * The original array is not mutated.
 *
 * @param items - Array of items with optional significance and score fields
 * @returns New sorted array ordered by significance then score
 */
export function rankBySignificance<
  T extends {
    significance?: string | undefined;
    overallScore?: number | undefined;
    cohesionScore?: number | undefined;
  },
>(items: T[]): T[] {
  return [...items].sort((a, b) => {
    const sigA = SIGNIFICANCE_WEIGHTS[a.significance ?? ''] ?? 0;
    const sigB = SIGNIFICANCE_WEIGHTS[b.significance ?? ''] ?? 0;
    if (sigA !== sigB) return sigB - sigA;
    const scoreA = a.overallScore ?? a.cohesionScore ?? 0;
    const scoreB = b.overallScore ?? b.cohesionScore ?? 0;
    return scoreB - scoreA;
  });
}
 
/**
 * Build an HTML section element for displaying intelligence items as a list.
 * All title, className, and item strings are HTML-escaped to prevent XSS.
 * Returns an empty string when the items array is empty.
 *
 * @param title - Section heading text (will be HTML-escaped)
 * @param items - Array of text items to display as list entries (will be HTML-escaped)
 * @param className - CSS class name for the section element (will be HTML-escaped)
 * @returns HTML string for the intelligence section, or empty string if no items
 */
export function buildIntelligenceSection(
  title: string,
  items: string[],
  className: string
): string {
  if (items.length === 0) return '';
  const safeClass = escapeHTML(className);
  const safeTitle = escapeHTML(title);
  const itemsHtml = items.map((item) => `<li>${escapeHTML(item)}</li>`).join('\n          ');
  return `<section class="${safeClass}">
        <h2>${safeTitle}</h2>
        <ul>
          ${itemsHtml}
        </ul>
      </section>`;
}
 
// ─── Stakeholder scoring functions ───────────────────────────────────────────
 
/**
 * Derive a severity level from a numeric 0-1 importance score.
 *
 * @param score - Normalised importance score (0 = least important, 1 = most)
 * @returns Severity level
 */
function severityFromScore(score: number): StakeholderPerspective['severity'] {
  if (score >= 0.7) return 'high';
  if (score >= 0.4) return 'medium';
  return 'low';
}
 
/**
 * Build a default set of stakeholder perspectives for a parliamentary action.
 * Each perspective is seeded with a reasoning string and evidence items derived
 * from the provided topic and impact scores. All six stakeholder groups receive
 * a perspective entry.
 *
 * @param topic - Short description of the parliamentary action (e.g. vote title)
 * @param scores - Optional per-stakeholder importance scores (0-1); defaults to 0.5
 * @returns Array of six StakeholderPerspective objects, one per stakeholder group
 */
export function buildDefaultStakeholderPerspectives(
  topic: string,
  scores?: Partial<Record<AnalysisStakeholderType, number>>
): StakeholderPerspective[] {
  return ALL_STAKEHOLDER_TYPES.map((stakeholder) => {
    const score = scores?.[stakeholder] ?? 0.5;
    const severity = severityFromScore(score);
    return {
      stakeholder,
      impact:
        score >= 0.6
          ? ('positive' as const)
          : score <= 0.3
            ? ('negative' as const)
            : ('neutral' as const),
      severity,
      reasoning: `Impact on this stakeholder group: ${severity} significance based on "${topic}".`,
      evidence: [topic],
    };
  });
}
 
/**
 * Score stakeholder influence from raw MCP data.
 * Returns null for null, undefined, non-object, or missing stakeholder type.
 *
 * @param rawData - Raw stakeholder influence data (unknown shape)
 * @returns Structured StakeholderPerspective or null if input is invalid
 */
export function scoreStakeholderInfluence(rawData: unknown): StakeholderPerspective | null {
  const d = toRecord(rawData);
  if (!d) return null;
  const stakeholderRaw = asStr(d['stakeholder']);
  if (!(ALL_STAKEHOLDER_TYPES as readonly string[]).includes(stakeholderRaw)) return null;
  const stakeholder = stakeholderRaw as AnalysisStakeholderType;
  const impactRaw = asStr(d['impact']).toLowerCase();
  const validImpacts = ['positive', 'negative', 'neutral', 'mixed'] as const;
  const impact = (validImpacts as readonly string[]).includes(impactRaw)
    ? (impactRaw as StakeholderPerspective['impact'])
    : 'neutral';
  const severityRaw = asStr(d['severity']).toLowerCase();
  const validSeverities = ['high', 'medium', 'low'] as const;
  const severity = (validSeverities as readonly string[]).includes(severityRaw)
    ? (severityRaw as StakeholderPerspective['severity'])
    : 'medium';
  return {
    stakeholder,
    impact,
    severity,
    reasoning: asStr(d['reasoning']),
    evidence: asStrArr(d['evidence']),
  };
}
 
/**
 * Build a StakeholderOutcomeMatrix row for a single parliamentary action.
 * Derives outcomes from per-stakeholder scores: score > 0.6 → winner,
 * score < 0.4 → loser, otherwise neutral.
 *
 * @param action - The parliamentary action being assessed
 * @param scores - Per-stakeholder importance scores (0-1); defaults to 0.5
 * @param confidence - Confidence level for the outcome assessments
 * @returns A StakeholderOutcomeMatrix row
 */
export function buildStakeholderOutcomeMatrix(
  action: string,
  scores: Partial<Record<AnalysisStakeholderType, number>> = {},
  confidence: StakeholderOutcomeMatrix['confidence'] = 'medium'
): StakeholderOutcomeMatrix {
  const outcomes = Object.fromEntries(
    ALL_STAKEHOLDER_TYPES.map((stakeholder) => {
      const score = scores[stakeholder] ?? 0.5;
      const outcome: 'winner' | 'loser' | 'neutral' =
        score > 0.6 ? 'winner' : score < 0.4 ? 'loser' : 'neutral';
      return [stakeholder, outcome];
    })
  ) as Record<AnalysisStakeholderType, 'winner' | 'loser' | 'neutral'>;
  return { action, outcomes, confidence };
}
 
/**
 * Map an array of StakeholderPerspective objects to a simple influence ranking.
 * Returns stakeholder types sorted by severity (high → medium → low), then by
 * impact direction (negative before positive, as negative impacts require more
 * political attention).
 *
 * @param perspectives - Array of stakeholder perspectives to rank
 * @returns Stakeholder types sorted by influence priority
 */
export function rankStakeholdersByInfluence(
  perspectives: readonly StakeholderPerspective[]
): AnalysisStakeholderType[] {
  const severityWeight: Record<StakeholderPerspective['severity'], number> = {
    high: 3,
    medium: 2,
    low: 1,
  };
  const impactWeight: Record<StakeholderPerspective['impact'], number> = {
    negative: 3,
    mixed: 2,
    positive: 1,
    neutral: 0,
  };
  return [...perspectives]
    .sort((a, b) => {
      const sw = severityWeight[b.severity] - severityWeight[a.severity];
      if (sw !== 0) return sw;
      const iw = impactWeight[b.impact] - impactWeight[a.impact];
      Eif (iw !== 0) return iw;
      // Deterministic tie-breaker: canonical ALL_STAKEHOLDER_TYPES order
      return (
        ALL_STAKEHOLDER_TYPES.indexOf(a.stakeholder) - ALL_STAKEHOLDER_TYPES.indexOf(b.stakeholder)
      );
    })
    .map((p) => p.stakeholder);
}
 
// ─── Advanced political intelligence functions ──────────────────────────────
 
/**
 * Compute voting intensity metrics from a set of voting records.
 * Analyses the distribution of for/against/abstain votes to determine
 * unanimity, polarization, and margin characteristics.
 *
 * @param records - Voting records to analyse
 * @returns VotingIntensity metrics, or null if the records array is empty or contains no
 * valid vote counts (for example, when all records have a total vote count of 0)
 */
export function computeVotingIntensity(records: readonly VotingRecord[]): VotingIntensity | null {
  if (records.length === 0) return null;
 
  let totalUnanimity = 0;
  let totalPolarization = 0;
  let totalMargin = 0;
  let closeVoteCount = 0;
  let decisiveVoteCount = 0;
 
  let validCount = 0;
  let polarizationCount = 0;
  for (const record of records) {
    const total = record.votes.for + record.votes.against + record.votes.abstain;
    if (total === 0) continue;
    validCount++;
 
    const forPct = record.votes.for / total;
    const againstPct = record.votes.against / total;
    const abstainPct = record.votes.abstain / total;
    const margin = Math.abs(forPct - againstPct);
 
    // Largest-position share: max share among for/against/abstain
    const maxPct = Math.max(forPct, againstPct, abstainPct);
    totalUnanimity += maxPct;
 
    // Margin, close/decisive, and polarization only meaningful when for+against > 0
    const forAgainstTotal = record.votes.for + record.votes.against;
    if (forAgainstTotal > 0) {
      polarizationCount++;
      const balance = Math.min(record.votes.for, record.votes.against) / forAgainstTotal;
      totalPolarization += balance * 2; // normalise: 0 = one-sided, 1 = perfectly split
 
      totalMargin += margin;
      if (margin < 0.1) closeVoteCount++;
      if (margin > 0.6) decisiveVoteCount++;
    }
  }
 
  if (validCount === 0) return null;
 
  return {
    unanimity: Math.round((totalUnanimity / validCount) * 100) / 100,
    polarization:
      polarizationCount > 0 ? Math.round((totalPolarization / polarizationCount) * 100) / 100 : 0,
    averageMargin:
      polarizationCount > 0 ? Math.round((totalMargin / polarizationCount) * 100) / 100 : 0,
    closeVoteCount,
    decisiveVoteCount,
  };
}
 
/**
 * Detect coalition shifts by comparing current cohesion patterns against
 * a baseline. Stability threshold is ±5%; severity tiers are >5% (medium),
 * >10% (high), and >20% (critical).
 *
 * @param currentPatterns - Current period voting patterns
 * @param baselinePatterns - Previous period patterns (or estimated baseline)
 * @returns Array of detected coalition shifts, sorted by significance
 */
export function detectCoalitionShifts(
  currentPatterns: readonly VotingPattern[],
  baselinePatterns: readonly VotingPattern[]
): CoalitionShift[] {
  const baselineMap = new Map<string, number>();
  for (const bp of baselinePatterns) {
    baselineMap.set(bp.group, bp.cohesion);
  }
 
  const shifts: CoalitionShift[] = [];
  for (const current of currentPatterns) {
    const previous = baselineMap.get(current.group) ?? current.cohesion;
    const delta = current.cohesion - previous;
    const absDelta = Math.abs(delta);
 
    let direction: CoalitionShift['direction'];
    if (delta > 0.05) direction = 'strengthening';
    else if (delta < -0.05) direction = 'weakening';
    else direction = 'stable';
 
    let significance: CoalitionShift['significance'];
    if (absDelta > 0.2) significance = 'critical';
    else Iif (absDelta > 0.1) significance = 'high';
    else if (absDelta > 0.05) significance = 'medium';
    else significance = 'low';
 
    shifts.push({
      group: current.group,
      previousCohesion: Math.round(previous * 100) / 100,
      currentCohesion: Math.round(current.cohesion * 100) / 100,
      cohesionDelta: Math.round(delta * 100) / 100,
      direction,
      significance,
    });
  }
 
  // Sort by significance (critical first), then by absolute delta descending
  const sigOrder: Record<string, number> = { critical: 4, high: 3, medium: 2, low: 1 };
  return shifts.sort((a, b) => {
    const sigDiff = (sigOrder[b.significance] ?? 0) - (sigOrder[a.significance] ?? 0);
    Eif (sigDiff !== 0) return sigDiff;
    return Math.abs(b.cohesionDelta) - Math.abs(a.cohesionDelta);
  });
}
 
/**
 * Classify cohesion groups into high-cohesion and fragmented categories.
 *
 * @param patterns - Voting patterns
 * @returns Tuple of [highCohesionGroups, fragmentedGroups]
 */
function classifyCohesionGroups(patterns: readonly VotingPattern[]): [string[], string[]] {
  const high: string[] = [];
  const fragmented: string[] = [];
  for (const p of patterns) {
    if (p.cohesion > 0.8) high.push(p.group);
    if (p.cohesion < 0.5) fragmented.push(p.group);
  }
  return [high, fragmented];
}
 
/**
 * Compute effective number of voting blocs using Laakso-Taagepera style.
 *
 * @param patterns - Voting patterns
 * @returns Effective number of blocs
 */
function computeEffectiveBlocs(patterns: readonly VotingPattern[]): number {
  let totalParticipation = 0;
  for (const p of patterns) totalParticipation += p.participation;
  Iif (totalParticipation <= 0) return patterns.length;
  let sumSquares = 0;
  for (const p of patterns) {
    const share = p.participation / totalParticipation;
    sumSquares += share * share;
  }
  return sumSquares > 0 ? 1 / sumSquares : patterns.length;
}
 
/**
 * Map an overall index to a polarization assessment label.
 *
 * @param index - Polarization index (0-1)
 * @returns Assessment label
 */
function assessPolarization(index: number): PolarizationIndex['assessment'] {
  if (index >= 0.75) return 'highly-polarized';
  if (index >= 0.5) return 'polarized';
  Iif (index >= 0.25) return 'moderate';
  return 'consensus';
}
 
/**
 * Compute a polarization index for a parliamentary period based on
 * voting pattern cohesion data. Uses a Laakso-Taagepera–inspired
 * "effective number of blocs" calculation alongside cohesion analysis.
 *
 * @param patterns - Voting patterns for the period
 * @returns PolarizationIndex assessment, or null if patterns are empty
 */
export function computePolarizationIndex(
  patterns: readonly VotingPattern[]
): PolarizationIndex | null {
  if (patterns.length === 0) return null;
 
  const [highCohesionGroups, fragmentedGroups] = classifyCohesionGroups(patterns);
  const effectiveBlocs = computeEffectiveBlocs(patterns);
 
  const extremeCount = highCohesionGroups.length + fragmentedGroups.length;
  const overallIndex = Math.round((extremeCount / patterns.length) * 100) / 100;
 
  return {
    overallIndex,
    effectiveBlocs: Math.round(effectiveBlocs * 100) / 100,
    highCohesionGroups,
    fragmentedGroups,
    assessment: assessPolarization(overallIndex),
  };
}
 
// ─── Cross-session analysis functions ─────────────────────────────────────────
 
/**
 * Compute average of a numeric array.
 *
 * @param values - Array of numbers
 * @returns Arithmetic mean, or 0 for empty arrays
 */
function avg(values: readonly number[]): number {
  return values.length > 0 ? values.reduce((s, v) => s + v, 0) / values.length : 0;
}
 
/**
 * Extract valid vote margins and result tallies from voting records.
 * Skips records with missing/malformed vote data, non-finite or negative
 * vote counts, or where for + against is zero (abstain-only votes) to avoid
 * skewing margin and polarization calculations. Only records where
 * `votes.for` and `votes.against` are finite, non-negative numbers are used;
 * numeric-string encodings and other non-numeric values are ignored.
 *
 * @param records - Voting records to process
 * @returns Object containing margins array and per-record result classifications
 */
function extractMarginData(records: readonly VotingRecord[]): {
  margins: number[];
  results: Array<'adopted' | 'rejected' | 'other'>;
} {
  const margins: number[] = [];
  const results: Array<'adopted' | 'rejected' | 'other'> = [];
 
  for (const r of records) {
    const votes = r.votes;
    if (!votes || typeof votes !== 'object') continue;
 
    // Require actual finite numbers — asNum() would silently map non-numbers to 0,
    // which would include malformed records and skew margins/polarization metrics.
    const forCount = votes.for;
    const againstCount = votes.against;
    Iif (typeof forCount !== 'number' || !Number.isFinite(forCount) || forCount < 0) continue;
    Iif (typeof againstCount !== 'number' || !Number.isFinite(againstCount) || againstCount < 0)
      continue;
 
    const forAgainstTotal = forCount + againstCount;
    if (forAgainstTotal <= 0) continue;
 
    margins.push(Math.abs(forCount - againstCount) / forAgainstTotal);
    const result = asStr(r.result).toLowerCase();
    if (result === 'adopted' || result === 'approved') {
      results.push('adopted');
    } else if (result === 'rejected') {
      results.push('rejected');
    } else E{
      results.push('other');
    }
  }
 
  return { margins, results };
}
 
/**
 * Compute adoption rate from a results slice.
 *
 * @param results - Array of result classifications
 * @returns Adoption rate (0-1), or 0 if no decided records
 */
function computeAdoptionRate(results: ReadonlyArray<'adopted' | 'rejected' | 'other'>): number {
  const adopted = results.filter((r) => r === 'adopted').length;
  const decided = results.filter((r) => r === 'adopted' || r === 'rejected').length;
  return decided > 0 ? adopted / decided : 0;
}
 
/**
 * Derive adoption-rate direction by comparing first-half and second-half rates.
 *
 * @param firstRate - Adoption rate of the first chronological half
 * @param secondRate - Adoption rate of the second chronological half
 * @returns Direction label based on delta between halves
 */
function adoptionDirection(firstRate: number, secondRate: number): VotingTrend['direction'] {
  const delta = secondRate - firstRate;
  if (delta > 0.05) return 'increasing';
  if (delta < -0.05) return 'decreasing';
  return 'stable';
}
 
/**
 * Build a margin-shift trend if the delta exceeds 5%.
 *
 * @param firstHalf - Margins from the first half of records
 * @param secondHalf - Margins from the second half of records
 * @param total - Total number of valid records
 * @returns VotingTrend or null if delta is within threshold
 */
function buildMarginTrend(
  firstHalf: number[],
  secondHalf: number[],
  total: number
): VotingTrend | null {
  const marginDelta = avg(secondHalf) - avg(firstHalf);
  if (Math.abs(marginDelta) <= 0.05) return null;
  const isIncreasing = marginDelta > 0;
  return {
    trendId: isIncreasing ? 'increasing-margins' : 'decreasing-margins',
    description: isIncreasing
      ? 'Voting margins are widening — greater decisiveness'
      : 'Voting margins are narrowing — increasing contention',
    direction: isIncreasing ? 'increasing' : 'decreasing',
    confidence: Math.min(1, Math.round(Math.abs(marginDelta) * 5 * 100) / 100),
    recordCount: total,
    metricValue: Math.round(marginDelta * 100) / 100,
  };
}
 
/**
 * Build a polarization trend if the close-vote frequency delta exceeds 10%.
 *
 * @param firstHalf - Margins from the first half of records
 * @param secondHalf - Margins from the second half of records
 * @param total - Total number of valid records
 * @returns VotingTrend or null if delta is within threshold
 */
function buildPolarizationTrend(
  firstHalf: number[],
  secondHalf: number[],
  total: number
): VotingTrend | null {
  const closeFirst = firstHalf.filter((m) => m < 0.1).length / firstHalf.length;
  const closeSecond = secondHalf.filter((m) => m < 0.1).length / secondHalf.length;
  const closeDelta = closeSecond - closeFirst;
  if (Math.abs(closeDelta) <= 0.1) return null;
  const isIncreasing = closeDelta > 0;
  return {
    trendId: isIncreasing ? 'increasing-polarization' : 'decreasing-polarization',
    description: isIncreasing
      ? 'More close votes detected — increasing polarization'
      : 'Fewer close votes — declining polarization',
    direction: isIncreasing ? 'increasing' : 'decreasing',
    confidence: Math.min(1, Math.round(Math.abs(closeDelta) * 3 * 100) / 100),
    recordCount: total,
    metricValue: Math.round(closeDelta * 100) / 100,
  };
}
 
/**
 * Detect voting trends across multiple voting records by analysing
 * margin distribution, polarization patterns, and result consistency.
 * Records are sorted by date (ascending) before analysis to ensure
 * chronological trend detection. Returns an array of detected trends
 * sorted by confidence.
 *
 * @param records - Voting records to analyse across sessions
 * @returns Array of detected VotingTrend objects (empty if fewer than 2 valid records)
 */
export function detectVotingTrends(records: readonly VotingRecord[]): VotingTrend[] {
  if (records.length < 2) return [];
 
  const toTimestamp = (d: string | undefined): number => {
    const t = Date.parse(d ?? '');
    return Number.isFinite(t) ? t : Infinity;
  };
  const sorted = [...records].sort((a, b) => {
    const ta = toTimestamp(a.date);
    const tb = toTimestamp(b.date);
    if (ta === tb) return 0;
    return ta < tb ? -1 : 1;
  });
 
  const { margins, results } = extractMarginData(sorted);
  Iif (margins.length < 2) return [];
 
  const mid = Math.floor(margins.length / 2);
  const firstHalf = margins.slice(0, mid);
  const secondHalf = margins.slice(mid);
 
  const trends: VotingTrend[] = [];
 
  const marginTrend = buildMarginTrend(firstHalf, secondHalf, margins.length);
  if (marginTrend) trends.push(marginTrend);
 
  const polTrend = buildPolarizationTrend(firstHalf, secondHalf, margins.length);
  if (polTrend) trends.push(polTrend);
 
  const firstResults = results.slice(0, mid);
  const secondResults = results.slice(mid);
  const totalDecided = results.filter((r) => r === 'adopted' || r === 'rejected').length;
  Eif (totalDecided > 0) {
    const overallRate = computeAdoptionRate(results);
    const firstRate = computeAdoptionRate(firstResults);
    const secondRate = computeAdoptionRate(secondResults);
    trends.push({
      trendId: 'adoption-rate',
      description: `Adoption rate is ${Math.round(overallRate * 100)}% across ${totalDecided} decided votes`,
      direction: adoptionDirection(firstRate, secondRate),
      confidence: Math.min(1, Math.round((totalDecided / margins.length) * 100) / 100),
      recordCount: totalDecided,
      metricValue: Math.round(overallRate * 100) / 100,
    });
  }
 
  return trends.sort((a, b) => b.confidence - a.confidence);
}
 
/**
 * Compute cross-session coalition stability by analysing average cohesion
 * across a set of voting patterns. Groups with high cohesion are reported
 * as stable; those with low cohesion are flagged.
 *
 * @param patterns - Voting patterns from multiple sessions
 * @returns CoalitionStabilityReport (empty report if no patterns)
 */
export function computeCrossSessionCoalitionStability(
  patterns: readonly VotingPattern[]
): CoalitionStabilityReport {
  if (patterns.length === 0) {
    return {
      overallStability: 0,
      patternCount: 0,
      stableGroups: [],
      decliningGroups: [],
      forecast: 'volatile',
    };
  }
 
  // Aggregate cohesion per group, coercing and clamping to [0, 1]
  const groupCohesions = new Map<string, number[]>();
  let includedPatterns = 0;
  for (const p of patterns) {
    const groupKey = asStr(p.group).trim();
    if (groupKey.length === 0) continue;
    includedPatterns++;
    const raw = asNum(p.cohesion);
    const clamped = Math.max(0, Math.min(1, raw));
    const existing = groupCohesions.get(groupKey);
    if (existing) {
      existing.push(clamped);
    } else {
      groupCohesions.set(groupKey, [clamped]);
    }
  }
 
  const stableGroups: string[] = [];
  const decliningGroups: string[] = [];
  let totalAvgCohesion = 0;
  let groupCount = 0;
 
  for (const [group, cohesions] of groupCohesions) {
    const avgCohesion = cohesions.reduce((s, v) => s + v, 0) / cohesions.length;
    totalAvgCohesion += avgCohesion;
    groupCount++;
 
    if (avgCohesion >= 0.7) {
      stableGroups.push(group);
    } else if (avgCohesion < 0.5) {
      decliningGroups.push(group);
    }
  }
 
  const overallStability =
    groupCount > 0 ? Math.round((totalAvgCohesion / groupCount) * 100) / 100 : 0;
 
  let forecast: CoalitionStabilityReport['forecast'];
  if (overallStability >= 0.7) forecast = 'stable';
  else if (overallStability >= 0.5) forecast = 'at-risk';
  else forecast = 'volatile';
 
  return {
    overallStability,
    patternCount: includedPatterns,
    stableGroups,
    decliningGroups,
    forecast,
  };
}
 
/**
 * Rank MEP influence scores filtered by topic relevance.
 * Matches scores whose mepName, mepId, or rank contains the topic substring
 * (case-insensitive). Returns the filtered list sorted by overallScore
 * descending. If topic is empty or no matches found, returns all scores
 * sorted by overallScore.
 *
 * @param scores - MEP influence scores to rank
 * @param topic - Topic keyword to filter by; if null/undefined/empty, all
 * scores are returned sorted by overallScore
 * @returns Sorted array of matching MEPInfluenceScore entries
 */
export function rankMEPInfluenceByTopic(
  scores: readonly MEPInfluenceScore[],
  topic: string | null | undefined
): MEPInfluenceScore[] {
  if (scores.length === 0) return [];
 
  const lowerTopic = String(topic ?? '')
    .toLowerCase()
    .trim();
 
  const getSafeScore = (entry: MEPInfluenceScore): number => {
    const raw = asNum(entry.overallScore);
    return Number.isFinite(raw) ? raw : 0;
  };
 
  // If topic is empty, return all sorted by score
  if (lowerTopic.length === 0) {
    return [...scores].sort((a, b) => getSafeScore(b) - getSafeScore(a));
  }
 
  const matched = scores.filter((s) => {
    const safeName = typeof s.mepName === 'string' ? s.mepName.toLowerCase() : '';
    const safeRank = typeof s.rank === 'string' ? s.rank.toLowerCase() : '';
    const safeId = typeof s.mepId === 'string' ? s.mepId.toLowerCase() : '';
    return (
      safeName.includes(lowerTopic) || safeRank.includes(lowerTopic) || safeId.includes(lowerTopic)
    );
  });
 
  // If no matches, return all sorted
  const pool = matched.length > 0 ? matched : [...scores];
  return pool.sort((a, b) => getSafeScore(b) - getSafeScore(a));
}
 
/**
 * Count stages whose document count exceeds 1.5× the average (bottlenecks).
 *
 * @param stageValues - Array of per-stage document counts
 * @returns Number of bottleneck stages
 */
function countBottleneckStages(stageValues: readonly number[]): number {
  Iif (stageValues.length === 0) return 0;
  const avgPerStage = stageValues.reduce((s, v) => s + v, 0) / stageValues.length;
  let count = 0;
  for (const val of stageValues) {
    if (val > avgPerStage * 1.5 && val > 1) count++;
  }
  return count;
}
 
/**
 * Compute average days per stage from a set of valid timestamps and the
 * number of stages. Returns 0 when fewer than 2 dates are available.
 *
 * @param dates - Array of valid timestamp numbers (ms since epoch)
 * @param stageCount - Number of distinct stages
 * @returns Estimated average days per stage (rounded)
 */
function computeDaysPerStage(dates: readonly number[], stageCount: number): number {
  if (dates.length < 2 || stageCount <= 0) return 0;
  let minDate = dates[0] as number;
  let maxDate = dates[0] as number;
  for (let i = 1; i < dates.length; i++) {
    const current = dates[i] as number;
    Iif (current < minDate) minDate = current;
    Eif (current > maxDate) maxDate = current;
  }
  const spanDays = (maxDate - minDate) / (1000 * 60 * 60 * 24);
  return Math.round(spanDays / stageCount);
}
 
/**
 * Determine throughput assessment label based on date availability and
 * average days per stage.
 *
 * @param hasDateData - Whether sufficient date data was available
 * @param avgDays - Average days per stage
 * @returns Throughput label: 'fast', 'normal', or 'slow'
 */
function assessThroughput(
  hasDateData: boolean,
  avgDays: number
): LegislativeVelocityReport['throughputAssessment'] {
  if (!hasDateData) return 'normal';
  if (avgDays <= 30) return 'fast';
  if (avgDays <= 90) return 'normal';
  return 'slow';
}
 
/**
 * Build a legislative velocity report with stage-by-stage breakdown from
 * a set of legislative documents. Analyses document status distribution
 * and identifies potential bottlenecks.
 *
 * @param docs - Legislative documents to analyse
 * @returns LegislativeVelocityReport summary
 */
export function buildLegislativeVelocityReport(
  docs: readonly LegislativeDocument[]
): LegislativeVelocityReport {
  if (docs.length === 0) {
    return {
      documentCount: 0,
      stageBreakdown: Object.create(null) as Record<string, number>,
      averageDaysPerStage: 0,
      bottleneckCount: 0,
      throughputAssessment: assessThroughput(false, 0),
    };
  }
 
  const stageBreakdown: Record<string, number> = Object.create(null) as Record<string, number>;
  for (const doc of docs) {
    const status = typeof doc.status === 'string' ? doc.status.trim() : '';
    const type = typeof doc.type === 'string' ? doc.type.trim() : '';
    const rawStage = status || type || 'Unknown';
    const stage =
      rawStage === '__proto__' || rawStage === 'constructor' || rawStage === 'prototype'
        ? 'Unknown'
        : rawStage;
    stageBreakdown[stage] = (stageBreakdown[stage] ?? 0) + 1;
  }
 
  const bottleneckCount = countBottleneckStages(Object.values(stageBreakdown));
 
  const dates = docs
    .map((d) => (d.date ? new Date(d.date).getTime() : NaN))
    .filter((t) => !Number.isNaN(t));
 
  const hasDateData = dates.length >= 2;
  const averageDaysPerStage = computeDaysPerStage(dates, Object.keys(stageBreakdown).length);
 
  return {
    documentCount: docs.length,
    stageBreakdown,
    averageDaysPerStage,
    bottleneckCount,
    throughputAssessment: assessThroughput(hasDateData, averageDaysPerStage),
  };
}