All files / src/generators/builders voting-builders.ts

98.75% Statements 159/161
92.63% Branches 151/163
100% Functions 70/70
100% Lines 125/125

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                                                                                                                                                      60x   60x 88x 53x         35x 18x               60x 69x 51x             60x                           60x 60x 69x 69x                   60x 70x 70x 70x                 60x                   60x 70x   33x                                           60x 60x                                                                         60x 7x   53x 53x 51x                   60x                   60x                           37x   36x           37x         37x                   42x       42x                                                 37x 3x                         6x           6x                                             37x 37x                                               5x                                                                                                         77x 94x 74x 60x   69x 60x 69x   69x     60x 60x   60x                               88x   53x       69x                                                                                         47x 54x 62x 52x 47x 56x 56x   49x   47x                                                                                                                                                                                       37x 39x 42x 39x 39x 37x 39x     37x                             37x     42x                       42x       42x               37x 37x 37x 37x   37x               37x                                         45x 47x 48x 45x   45x   39x 41x 41x 41x   41x                   41x                     39x 41x           47x   41x   39x                 39x 39x               39x   39x                                                         5x 5x   8x 12x 8x 8x 12x 12x 8x   5x                           5x                   5x                       5x                   5x                       5x     12x 8x   9x       5x                   5x              
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/Builders/VotingBuilders
 * @description Deep analysis, SWOT, dashboard, mindmap and multi-dimensional SWOT
 * builders for voting-based articles (motions, weekly/monthly review).
 */
 
import type {
  DeepAnalysis,
  StakeholderOutcome,
  ActionConsequence,
  PoliticalMistake,
  VotingRecord,
  VotingPattern,
  VotingAnomaly,
  MotionsQuestion,
  LanguageCode,
  SwotAnalysis,
  DashboardConfig,
  SwotBuilderStrings,
  DashboardBuilderStrings,
  IntelligenceMindmap,
  MindmapNode,
  ActorNode,
  PolicyConnection,
  StakeholderPerspective,
  CoalitionMetrics,
  MultiDimensionalSwot,
  TemporalSwotAssessment,
  StakeholderType,
  VotingIntensity,
  PolarizationIndex,
  DashboardPanel,
} from '../../types/index.js';
import {
  getLocalizedString,
  SWOT_BUILDER_STRINGS,
  DASHBOARD_BUILDER_STRINGS,
} from '../../constants/languages.js';
import { PLACEHOLDER_MARKER } from '../motions-content.js';
import {
  buildDefaultStakeholderPerspectives,
  computeVotingIntensity,
  computePolarizationIndex,
} from '../../utils/intelligence-analysis.js';
import { AI_MARKER } from '../../constants/analysis-constants.js';
import {
  buildOutcomeMatrix,
  buildAiMarkerImpactAssessment,
  buildCoalitionMetricsFromPatterns,
  buildStakeholderMetricsFromVoting,
  buildStakeholderPanel,
  makeDimension,
  EP_BLUE_TRANSPARENT,
  EP_BLUE_BORDER,
  CIVIL_SOCIETY,
} from './shared-builders.js';
 
/**
 * Derive stakeholder outcomes from voting records.
 * Groups with high cohesion (>0.8) and high participation (>0.7) are treated as
 * "winners"; groups with low cohesion (<0.5) are flagged as "at risk".
 * Returns `{actor, outcome, reason}` where `reason` is set to `AI_MARKER`
 * so the AI enrichment step provides substantive political reasoning.
 *
 * @param records - Voting records
 * @param patterns - Voting pattern data
 * @returns Stakeholder outcome assessments with `reason` set to `AI_MARKER`
 */
function deriveStakeholderOutcomesFromVoting(
  records: readonly VotingRecord[],
  patterns: readonly VotingPattern[]
): StakeholderOutcome[] {
  const outcomes: StakeholderOutcome[] = [];
  // High-cohesion groups with strong participation are classified as winners
  for (const pattern of patterns) {
    if (pattern.cohesion > 0.8 && pattern.participation > 0.7) {
      outcomes.push({
        actor: pattern.group,
        outcome: 'winner',
        reason: AI_MARKER,
      });
    } else if (pattern.cohesion < 0.5) {
      outcomes.push({
        actor: pattern.group,
        outcome: 'loser',
        reason: AI_MARKER,
      });
    }
  }
  // Adopted motions → the proposing side wins
  for (const record of records.slice(0, 3)) {
    if (record.result?.toLowerCase().includes('adopt')) {
      outcomes.push({
        actor: 'Majority coalition',
        outcome: 'winner',
        reason: AI_MARKER,
      });
    }
  }
  return outcomes;
}
 
/**
 * Derive action→consequence chains from voting records and anomalies.
 *
 * @param records - Voting records
 * @param anomalies - Detected anomalies
 * @returns Action-consequence pairs
 */
function deriveConsequencesFromVoting(
  records: readonly VotingRecord[],
  anomalies: readonly VotingAnomaly[]
): ActionConsequence[] {
  const consequences: ActionConsequence[] = [];
  for (const record of records.slice(0, 3)) {
    Iif (record.result === PLACEHOLDER_MARKER) continue;
    consequences.push({
      action: `Vote on "${record.title}" (result: ${record.result}; ${record.votes.for} for, ${record.votes.against} against, ${record.votes.abstain} abstentions)`,
      consequence: AI_MARKER,
      severity:
        Math.abs(record.votes.for - record.votes.against) >
        (record.votes.for + record.votes.against) / 2
          ? 'high'
          : 'medium',
    });
  }
  for (const anomaly of anomalies.slice(0, 2)) {
    Iif (/placeholder/i.test(anomaly.type)) continue;
    const anomalyDescription: string = anomaly.description?.trim() ?? '';
    consequences.push({
      action:
        anomalyDescription.length > 0
          ? `${anomaly.type} detected: ${anomalyDescription}`
          : `${anomaly.type} detected`,
      consequence: AI_MARKER,
      severity: anomaly.severity?.toLowerCase() === 'high' ? 'high' : 'medium',
    });
  }
  return consequences;
}
 
/**
 * Derive political mistakes from anomalies — defections signal miscalculations.
 *
 * @param anomalies - Detected voting anomalies
 * @returns Political mistake assessments
 */
function deriveMistakesFromAnomalies(anomalies: readonly VotingAnomaly[]): PoliticalMistake[] {
  return anomalies
    .filter((a) => a.type?.toLowerCase().includes('defect') || a.severity?.toUpperCase() === 'HIGH')
    .slice(0, 3)
    .map((a) => ({
      actor: 'Political group leadership',
      description: `${a.type}: ${a.description}`,
      alternative: AI_MARKER,
    }));
}
 
/**
 * Build multi-stakeholder perspectives for a voting analysis.
 * Derives per-group importance scores based on adopted/rejected counts and
 * cohesion anomalies.
 *
 * @param adoptedCount - Number of adopted texts
 * @param anomalies - Detected voting anomalies
 * @param topic - Primary topic string for context
 * @returns Array of stakeholder perspectives
 */
function buildVotingStakeholderPerspectives(
  adoptedCount: number,
  anomalies: readonly VotingAnomaly[],
  topic: string
): StakeholderPerspective[] {
  const hasHighAnomalies = anomalies.some((a) => a.severity?.toUpperCase() === 'HIGH');
  return buildDefaultStakeholderPerspectives(topic, {
    political_groups: hasHighAnomalies ? 0.9 : adoptedCount > 0 ? 0.8 : 0.5,
    civil_society: adoptedCount > 0 ? 0.6 : 0.4,
    industry: adoptedCount > 0 ? 0.7 : 0.4,
    national_govts: 0.7,
    citizens: adoptedCount > 0 ? 0.6 : 0.3,
    eu_institutions: 0.8,
  });
}
 
/**
 * Build the "what" summary for a voting analysis, including intensity metrics.
 *
 * @param dateFrom - Period start
 * @param dateTo - Period end
 * @param recordCount - Real voting record count
 * @param adoptedCount - Adopted count
 * @param rejectedCount - Rejected count
 * @param anomalyCount - Anomaly count
 * @param patternCount - Pattern count
 * @param questionCount - Question count
 * @param intensity - Voting intensity metrics (may be null)
 * @param polarization - Polarization index (may be null)
 * @returns Summary text
 */
function buildVotingWhatText(
  dateFrom: string,
  dateTo: string,
  recordCount: number,
  adoptedCount: number,
  rejectedCount: number,
  anomalyCount: number,
  patternCount: number,
  questionCount: number,
  intensity: VotingIntensity | null,
  polarization: PolarizationIndex | null
): string {
  if (recordCount === 0 && patternCount === 0 && questionCount === 0) {
    return `Parliamentary activity from ${dateFrom} to ${dateTo}. Detailed roll-call data unavailable for this period.`;
  }
  const base = `${recordCount} votes recorded between ${dateFrom} and ${dateTo}: ${adoptedCount} adopted, ${rejectedCount} rejected. ${anomalyCount} voting anomalies detected across ${patternCount} political groups. ${questionCount} parliamentary questions filed.`;
  if (!intensity || recordCount === 0) return base;
  return `${base} Voting intensity: ${intensity.closeVoteCount} close ${intensity.closeVoteCount === 1 ? 'vote' : 'votes'}, ${intensity.decisiveVoteCount} decisive ${intensity.decisiveVoteCount === 1 ? 'vote' : 'votes'}. Polarization index: ${polarization?.assessment ?? 'N/A'}.`;
}
 
/**
 * Build the "why" text for a voting analysis.
 * Returns AI_MARKER so the AI agent provides real political analysis.
 *
 * @returns AI_MARKER placeholder for AI-driven analysis
 */
function buildVotingWhyText(): string {
  return AI_MARKER;
}
 
/**
 * Build outlook text for voting analysis.
 * Returns AI_MARKER — the AI agent provides real forward-looking analysis.
 *
 * @returns AI_MARKER placeholder
 */
function buildVotingOutlook(): string {
  return AI_MARKER;
}
 
/**
 * Build the coalition alignment panel for a voting dashboard.
 *
 * @param d - Localized dashboard strings
 * @param coalition - Coalition metrics
 * @returns Panel object or null
 */
function buildVotingCoalitionPanel(
  d: DashboardBuilderStrings,
  coalition: CoalitionMetrics | null
): DashboardPanel | null {
  if (!coalition) return null;
  const shiftLabel =
    coalition.shiftIndicator === 'strengthening'
      ? d.coalitionStrengthening
      : coalition.shiftIndicator === 'weakening'
        ? d.coalitionWeakening
        : d.coalitionStable;
  const shiftTrend: 'up' | 'down' | 'stable' =
    coalition.shiftIndicator === 'strengthening'
      ? 'up'
      : coalition.shiftIndicator === 'weakening'
        ? 'down'
        : 'stable';
  return {
    title: d.coalitionAlignment,
    metrics: [
      { label: d.alignmentScore, value: `${coalition.alignmentScore}%`, trend: shiftTrend },
      { label: d.coalitionShift, value: shiftLabel },
    ],
    chart: {
      type: 'radar' as const,
      title: d.coalitionRadarChart,
      data: {
        labels: coalition.votingBlocs.map((b) => b.group),
        datasets: [
          {
            label: d.alignmentScore,
            data: coalition.votingBlocs.map((b) => b.alignmentScore),
            backgroundColor: EP_BLUE_TRANSPARENT,
            borderColor: EP_BLUE_BORDER,
          },
        ],
      },
    },
  };
}
 
/**
 * Build the trend panel for a voting dashboard.
 *
 * @param d - Localized dashboard strings
 * @param realRecords - Filtered real voting records
 * @param adoptedCount - Number of adopted votes
 * @param rejectedCount - Number of rejected votes
 * @returns Panel object or null
 */
function buildVotingTrendPanel(
  d: DashboardBuilderStrings,
  realRecords: readonly VotingRecord[],
  adoptedCount: number,
  rejectedCount: number
): DashboardPanel | null {
  if (realRecords.length < 2) return null;
  return {
    title: d.trendAnalysis,
    metrics: [
      {
        label: d.adopted,
        value: String(adoptedCount),
        trend: (adoptedCount > rejectedCount ? 'up' : 'stable') as 'up' | 'down' | 'stable',
      },
    ],
    chart: {
      type: 'line' as const,
      title: d.activityTrendChart,
      data: {
        labels: realRecords.slice(0, 6).map((r) => r.date ?? ''),
        datasets: [
          {
            label: d.adopted,
            data: realRecords
              .slice(0, 6)
              .map((r) => (r.result?.toLowerCase().includes('adopt') ? 1 : 0)),
            borderColor: '#28a745',
            backgroundColor: 'rgba(40,167,69,0.1)',
          },
        ],
      },
    },
  };
}
 
/**
 * Build the stakeholder panel for a voting dashboard.
 *
 * @param d - Localized dashboard strings
 * @param patterns - Voting patterns
 * @param anomalyCount - Number of voting anomalies
 * @returns Panel object or null
 */
function buildVotingStakeholderPanel(
  d: DashboardBuilderStrings,
  patterns: readonly VotingPattern[],
  anomalyCount: number
): DashboardPanel | null {
  const stakeholderMetrics = buildStakeholderMetricsFromVoting(patterns, anomalyCount);
  return buildStakeholderPanel(d, stakeholderMetrics);
}
 
/**
 * Build stakeholder views for voting multi-dimensional SWOT.
 *
 * @param adoptedCount - Number of adopted votes
 * @param realAnomalies - Non-placeholder anomalies
 * @param highSeverity - High-severity anomalies
 * @param highCohesion - High-cohesion patterns
 * @param lowCohesion - Low-cohesion patterns
 * @param realPatterns - Non-placeholder patterns
 * @param s - Localized SWOT builder strings
 * @returns Stakeholder views map
 */
function buildVotingMDStakeholders(
  adoptedCount: number,
  realAnomalies: readonly VotingAnomaly[],
  highSeverity: readonly VotingAnomaly[],
  highCohesion: readonly VotingPattern[],
  lowCohesion: readonly VotingPattern[],
  realPatterns: readonly VotingPattern[],
  s: SwotBuilderStrings
): Partial<Record<StakeholderType, SwotAnalysis>> {
  return {
    citizen: {
      strengths:
        adoptedCount > 0
          ? [{ text: s.votingAdopted(adoptedCount), severity: 'medium' as const }]
          : [],
      weaknesses:
        realAnomalies.length > 0
          ? [{ text: s.votingAnomalies(realAnomalies.length), severity: 'medium' as const }]
          : [],
      opportunities: [{ text: s.votingCrossParty, severity: 'medium' as const }],
      threats:
        highSeverity.length > 0
          ? [{ text: s.votingHighSeverity(highSeverity.length), severity: 'high' as const }]
          : [],
    },
    mep: {
      strengths:
        highCohesion.length > 0
          ? [{ text: s.votingHighCohesion(highCohesion.length), severity: 'high' as const }]
          : [],
      weaknesses:
        lowCohesion.length > 0
          ? [{ text: s.votingLowCohesion(lowCohesion.length), severity: 'high' as const }]
          : [],
      opportunities:
        realPatterns.length > 0
          ? [{ text: s.votingDiverseGroups(realPatterns.length), severity: 'medium' as const }]
          : [],
      threats: [{ text: s.votingShiftingAlliances, severity: 'medium' as const }],
    },
  };
}
 
/**
 * Build deep analysis for voting-based articles (motions, weekly/monthly review).
 *
 * @param dateFrom - Period start date
 * @param dateTo - Period end date
 * @param records - Voting records
 * @param patterns - Voting patterns
 * @param anomalies - Anomalies detected
 * @param questions - Parliamentary questions
 * @returns Deep analysis object
 */
export function buildVotingAnalysis(
  dateFrom: string,
  dateTo: string,
  records: readonly VotingRecord[],
  patterns: readonly VotingPattern[],
  anomalies: readonly VotingAnomaly[],
  questions: readonly MotionsQuestion[]
): DeepAnalysis {
  const realRecords = records.filter((r) => r.result !== PLACEHOLDER_MARKER);
  const realPatterns = patterns.filter((p) => !/placeholder/i.test(p.group));
  const realAnomalies = anomalies.filter((a) => !/placeholder/i.test(a.type));
  const realQuestions = questions.filter((q) => q.status !== PLACEHOLDER_MARKER);
 
  const adoptedCount = realRecords.filter((r) => r.result?.toLowerCase().includes('adopt')).length;
  const rejectedCount = realRecords.filter((r) =>
    r.result?.toLowerCase().includes('reject')
  ).length;
  const topTopics = realRecords.slice(0, 3).map((r) => r.title);
 
  // ── Advanced political intelligence ────────────────────────────────────────
  const intensity = computeVotingIntensity(realRecords);
  const polarization = computePolarizationIndex(realPatterns);
 
  return {
    what: buildVotingWhatText(
      dateFrom,
      dateTo,
      realRecords.length,
      adoptedCount,
      rejectedCount,
      realAnomalies.length,
      realPatterns.length,
      realQuestions.length,
      intensity,
      polarization
    ),
    who: [
      ...realPatterns.map(
        (p) =>
          `${p.group} — cohesion: ${(p.cohesion * 100).toFixed(0)}%, participation: ${(p.participation * 100).toFixed(0)}%`
      ),
      ...realQuestions.slice(0, 3).map((q) => `${q.author} — question on "${q.topic}"`),
    ],
    when: [
      `Period: ${dateFrom} to ${dateTo}`,
      ...realRecords.slice(0, 3).map((r) => `${r.date}: Vote on "${r.title}" — ${r.result}`),
    ],
    why: buildVotingWhyText(),
    stakeholderOutcomes: deriveStakeholderOutcomesFromVoting(realRecords, realPatterns),
    impactAssessment: buildAiMarkerImpactAssessment(),
    actionConsequences: deriveConsequencesFromVoting(realRecords, realAnomalies),
    mistakes: deriveMistakesFromAnomalies(realAnomalies),
    outlook: buildVotingOutlook(),
    stakeholderPerspectives: buildVotingStakeholderPerspectives(
      adoptedCount,
      realAnomalies,
      topTopics[0] ?? `voting period ${dateFrom}–${dateTo}`
    ),
    stakeholderOutcomeMatrix: buildOutcomeMatrix([
      {
        action: `Voting outcomes ${dateFrom}–${dateTo}`,
        scores: {
          political_groups: realAnomalies.length > 0 ? 0.8 : 0.6,
          civil_society: adoptedCount > 0 ? 0.6 : 0.4,
          industry: adoptedCount > 0 ? 0.7 : 0.4,
          national_govts: 0.7,
          citizens: adoptedCount > 0 ? 0.6 : 0.3,
          eu_institutions: 0.8,
        },
        confidence: realRecords.length > 0 ? 'high' : 'low',
      },
    ]),
  };
}
 
/**
 * Build SWOT analysis for voting-based articles (motions, weekly/monthly review).
 *
 * @param records - Voting records
 * @param patterns - Voting patterns
 * @param anomalies - Detected anomalies
 * @param lang - Target language code
 * @returns SWOT analysis data
 */
export function buildVotingSwot(
  records: readonly VotingRecord[],
  patterns: readonly VotingPattern[],
  anomalies: readonly VotingAnomaly[],
  lang: LanguageCode = 'en'
): SwotAnalysis {
  const s: SwotBuilderStrings = getLocalizedString(SWOT_BUILDER_STRINGS, lang);
  const realRecords = records.filter((r) => r.result !== PLACEHOLDER_MARKER);
  const realPatterns = patterns.filter((p) => !/placeholder/i.test(p.group));
  const realAnomalies = anomalies.filter((a) => !/placeholder/i.test(a.type));
  const adoptedCount = realRecords.filter((r) => r.result?.toLowerCase().includes('adopt')).length;
  const highCohesionGroups = realPatterns.filter((p) => p.cohesion > 0.8);
  const lowCohesionGroups = realPatterns.filter((p) => p.cohesion < 0.5);
 
  const highSeverityAnomalies = realAnomalies.filter((a) => a.severity?.toUpperCase() === 'HIGH');
 
  return {
    strengths: [
      ...(highCohesionGroups.length > 0
        ? [
            {
              text: s.votingHighCohesion(highCohesionGroups.length),
              severity: 'high' as const,
            },
          ]
        : []),
      ...(adoptedCount > 0
        ? [
            {
              text: s.votingAdopted(adoptedCount),
              severity: 'medium' as const,
            },
          ]
        : []),
      ...(realRecords.length > 0
        ? [
            {
              text: s.votingActiveVotes(realRecords.length),
              severity: 'medium' as const,
            },
          ]
        : []),
    ],
    weaknesses: [
      ...(lowCohesionGroups.length > 0
        ? [
            {
              text: s.votingLowCohesion(lowCohesionGroups.length),
              severity: 'high' as const,
            },
          ]
        : []),
      ...(realAnomalies.length > 0
        ? [
            {
              text: s.votingAnomalies(realAnomalies.length),
              severity: 'medium' as const,
            },
          ]
        : []),
    ],
    opportunities: [
      {
        text: s.votingCrossParty,
        severity: 'medium' as const,
      },
      ...(realPatterns.length > 0
        ? [
            {
              text: s.votingDiverseGroups(realPatterns.length),
              severity: 'medium' as const,
            },
          ]
        : []),
    ],
    threats: [
      ...(highSeverityAnomalies.length > 0
        ? [
            {
              text: s.votingHighSeverity(highSeverityAnomalies.length),
              severity: 'high' as const,
            },
          ]
        : []),
      {
        text: s.votingShiftingAlliances,
        severity: 'medium' as const,
      },
    ],
  };
}
 
/**
 * Build dashboard for voting-based articles (motions, weekly/monthly review).
 * Includes a coalition alignment radar chart and stakeholder impact scorecard.
 *
 * @param records - Voting records
 * @param patterns - Voting patterns
 * @param anomalies - Detected anomalies
 * @param lang - Target language code
 * @returns Dashboard configuration with coalition and stakeholder intelligence
 */
export function buildVotingDashboard(
  records: readonly VotingRecord[],
  patterns: readonly VotingPattern[],
  anomalies: readonly VotingAnomaly[],
  lang: LanguageCode = 'en'
): DashboardConfig {
  const d: DashboardBuilderStrings = getLocalizedString(DASHBOARD_BUILDER_STRINGS, lang);
  const realRecords = records.filter((r) => r.result !== PLACEHOLDER_MARKER);
  const realPatterns = patterns.filter((p) => !/placeholder/i.test(p.group));
  const realAnomalies = anomalies.filter((a) => !/placeholder/i.test(a.type));
  const adoptedCount = realRecords.filter((r) => r.result?.toLowerCase().includes('adopt')).length;
  const rejectedCount = realRecords.filter((r) =>
    r.result?.toLowerCase().includes('reject')
  ).length;
 
  const overviewPanel = {
    title: d.votingOverview,
    metrics: [
      { label: d.totalVotes, value: String(realRecords.length), trend: 'stable' as const },
      {
        label: d.adopted,
        value: String(adoptedCount),
        trend: adoptedCount > 0 ? ('up' as const) : ('stable' as const),
      },
      { label: d.rejected, value: String(rejectedCount) },
      { label: d.anomalies, value: String(realAnomalies.length) },
    ],
  };
 
  const cohesionPanel =
    realPatterns.length > 0
      ? {
          title: d.politicalGroupCohesion,
          metrics: realPatterns.slice(0, 4).map((p) => ({
            label: p.group,
            value: `${(p.cohesion * 100).toFixed(0)}%`,
            trend: (p.cohesion > 0.8 ? 'up' : p.cohesion < 0.5 ? 'down' : 'stable') as
              | 'up'
              | 'down'
              | 'stable',
          })),
          chart: {
            type: 'bar' as const,
            title: d.groupCohesionRates,
            data: {
              labels: realPatterns.slice(0, 6).map((p) => p.group),
              datasets: [
                {
                  label: d.cohesionPct,
                  data: realPatterns.slice(0, 6).map((p) => Math.round(p.cohesion * 100)),
                },
              ],
            },
          },
        }
      : null;
 
  const coalition = buildCoalitionMetricsFromPatterns(realPatterns);
  const coalitionPanel = buildVotingCoalitionPanel(d, coalition);
  const trendPanel = buildVotingTrendPanel(d, realRecords, adoptedCount, rejectedCount);
  const stakeholderPanel = buildVotingStakeholderPanel(d, realPatterns, realAnomalies.length);
 
  const panels = [
    overviewPanel,
    ...(cohesionPanel ? [cohesionPanel] : []),
    ...(coalitionPanel ? [coalitionPanel] : []),
    ...(trendPanel ? [trendPanel] : []),
    ...(stakeholderPanel ? [stakeholderPanel] : []),
  ];
 
  return { panels };
}
 
/**
 * Build intelligence mindmap for voting analysis articles.
 *
 * Constructs a policy domain intelligence map with political group nodes
 * as the primary domain layer, voting pattern sub-topics, and anomaly actors.
 *
 * @param records - Voting records for the period
 * @param patterns - Political group voting pattern data
 * @param anomalies - Detected voting anomalies
 * @param _lang - Reserved for future localisation (default: 'en')
 * @returns Intelligence mindmap data, or null when all data is placeholder
 */
export function buildVotingMindmap(
  records: readonly VotingRecord[],
  patterns: readonly VotingPattern[],
  anomalies: readonly VotingAnomaly[],
  _lang: LanguageCode = 'en'
): IntelligenceMindmap | null {
  void _lang;
  const realRecords = records.filter((r) => r.result !== PLACEHOLDER_MARKER);
  const realPatterns = patterns.filter((p) => !/placeholder/i.test(p.group));
  const realAnomalies = anomalies.filter((a) => !/placeholder/i.test(a.type));
 
  if (realPatterns.length === 0) return null;
 
  const domainNodes: MindmapNode[] = realPatterns.slice(0, 8).map((p, i) => {
    const cohesion = p.cohesion ?? 0;
    const children: MindmapNode[] = realRecords
      .filter((r) => r.result !== PLACEHOLDER_MARKER)
      .slice(0, 3)
      .map((r, ri) => ({
        id: `record-${i}-${ri}`,
        label: r.title.slice(0, 50),
        category: 'action' as const,
        influence: r.votes.for / Math.max(1, r.votes.for + r.votes.against + r.votes.abstain),
        color: r.result?.toLowerCase().includes('adopt') ? 'green' : 'red',
        children: [],
        metadata: { documentRef: r.title.slice(0, 30) },
      }));
 
    return {
      id: `group-${i}`,
      label: p.group,
      category: 'policy_domain' as const,
      influence: cohesion,
      color: cohesion > 0.8 ? 'green' : cohesion > 0.5 ? 'cyan' : 'red',
      children,
      metadata: { politicalGroup: p.group },
    };
  });
 
  const actorNetwork: ActorNode[] = [
    ...realPatterns.slice(0, 6).map((p, i) => ({
      id: `actor-group-${i}`,
      name: p.group,
      type: 'group' as const,
      influence: p.cohesion ?? 0,
      connections: realAnomalies
        .filter((a) => a.type && !a.type.includes('placeholder'))
        .slice(0, 2)
        .map((_, ai) => `anomaly-${ai}`),
    })),
    ...realAnomalies.slice(0, 3).map((a, i) => ({
      id: `anomaly-${i}`,
      name: a.type,
      type: 'external' as const,
      influence: a.severity?.toUpperCase() === 'HIGH' ? 0.9 : 0.5,
      connections: [],
    })),
  ];
 
  const anomalyActorCount = Math.min(realAnomalies.length, 3);
  const connections: PolicyConnection[] = realAnomalies.slice(0, anomalyActorCount).map((a, i) => ({
    from: `anomaly-${i}`,
    to: `group-${i % Math.max(1, domainNodes.length)}`,
    strength: a.severity?.toUpperCase() === 'HIGH' ? 'strong' : 'moderate',
    type: 'political' as const,
    evidence: a.type,
  }));
 
  const adoptedCount = realRecords.filter((r) => r.result?.toLowerCase().includes('adopt')).length;
 
  return {
    centralTopic: 'Voting Intelligence Analysis',
    layers: [{ depth: 1, nodes: domainNodes }],
    connections,
    actorNetwork,
    stakeholderGroups: ['Political Groups', CIVIL_SOCIETY, 'Member States'],
    summary: `Analysing ${realRecords.length} votes across ${realPatterns.length} political groups. ${adoptedCount} measures adopted.`,
  };
}
 
/**
 * Build multi-dimensional SWOT analysis for voting-based articles.
 *
 * Produces dimension-specific breakdowns (political, economic, social,
 * legal, geopolitical), temporal assessments, and stakeholder views
 * derived from voting records, patterns, and anomaly data.
 *
 * @param records - Voting records
 * @param patterns - Voting patterns
 * @param anomalies - Detected anomalies
 * @param lang - Target language code
 * @returns Multi-dimensional SWOT data
 */
export function buildVotingMultiDimensionalSwot(
  records: readonly VotingRecord[],
  patterns: readonly VotingPattern[],
  anomalies: readonly VotingAnomaly[],
  lang: LanguageCode = 'en'
): MultiDimensionalSwot {
  const s: SwotBuilderStrings = getLocalizedString(SWOT_BUILDER_STRINGS, lang);
  const base = buildVotingSwot(records, patterns, anomalies, lang);
 
  const realRecords = records.filter((r) => r.result !== PLACEHOLDER_MARKER);
  const realPatterns = patterns.filter((p) => !/placeholder/i.test(p.group));
  const realAnomalies = anomalies.filter((a) => !/placeholder/i.test(a.type));
  const adoptedCount = realRecords.filter((r) => r.result?.toLowerCase().includes('adopt')).length;
  const highCohesion = realPatterns.filter((p) => p.cohesion > 0.8);
  const lowCohesion = realPatterns.filter((p) => p.cohesion < 0.5);
  const highSeverity = realAnomalies.filter((a) => a.severity?.toUpperCase() === 'HIGH');
 
  const political = makeDimension(
    'political',
    highCohesion.length > 0
      ? [{ text: s.votingHighCohesion(highCohesion.length), severity: 'high' as const }]
      : [],
    lowCohesion.length > 0
      ? [{ text: s.votingLowCohesion(lowCohesion.length), severity: 'high' as const }]
      : [],
    [{ text: s.votingCrossParty, severity: 'medium' as const }],
    highSeverity.length > 0
      ? [{ text: s.votingHighSeverity(highSeverity.length), severity: 'high' as const }]
      : []
  );
 
  const economic = makeDimension(
    'economic',
    adoptedCount > 0 ? [{ text: s.votingAdopted(adoptedCount), severity: 'medium' as const }] : [],
    [],
    realPatterns.length > 0
      ? [{ text: s.votingDiverseGroups(realPatterns.length), severity: 'medium' as const }]
      : [],
    [{ text: s.votingShiftingAlliances, severity: 'medium' as const }]
  );
 
  const social = makeDimension(
    'social',
    realRecords.length > 0
      ? [{ text: s.votingActiveVotes(realRecords.length), severity: 'medium' as const }]
      : [],
    realAnomalies.length > 0
      ? [{ text: s.votingAnomalies(realAnomalies.length), severity: 'medium' as const }]
      : [],
    [],
    []
  );
 
  const legal = makeDimension(
    'legal',
    adoptedCount > 0 ? [{ text: s.votingAdopted(adoptedCount), severity: 'medium' as const }] : [],
    [],
    [],
    highSeverity.length > 0
      ? [{ text: s.votingHighSeverity(highSeverity.length), severity: 'high' as const }]
      : []
  );
 
  const geopolitical = makeDimension(
    'geopolitical',
    [],
    lowCohesion.length > 0
      ? [{ text: s.votingLowCohesion(lowCohesion.length), severity: 'medium' as const }]
      : [],
    highCohesion.length > 0
      ? [{ text: s.votingHighCohesion(highCohesion.length), severity: 'medium' as const }]
      : [],
    [{ text: s.votingShiftingAlliances, severity: 'medium' as const }]
  );
 
  const temporal: TemporalSwotAssessment = {
    shortTerm: base,
    mediumTerm: {
      strengths: base.strengths.filter((i) => i.severity === 'high'),
      weaknesses: base.weaknesses.filter((i) => i.severity === 'high'),
      opportunities: base.opportunities,
      threats: base.threats.filter((i) => i.severity === 'high'),
    },
  };
 
  const stakeholderViews = buildVotingMDStakeholders(
    adoptedCount,
    realAnomalies,
    highSeverity,
    highCohesion,
    lowCohesion,
    realPatterns,
    s
  );
 
  return {
    title: base.title,
    dimensions: [political, economic, social, legal, geopolitical],
    temporal,
    stakeholderViews,
  };
}