All files / generators deep-analysis-content.ts

95.1% Statements 175/184
83.45% Branches 116/139
100% Functions 50/50
98.19% Lines 163/166

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 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064                                                                                                      156x 156x 156x                               156x 150x 373x 156x                                   156x 155x 156x 318x   156x                                   156x 156x 156x                           310x                                 310x   152x   78x   80x                                           156x 136x 156x     310x           156x                                                                     156x 156x           780x 156x 155x     775x           155x                                                         294x   9x   152x   132x   1x                                                                         156x 148x 156x     294x               156x                                                                   156x 96x 156x     96x             156x                               156x 155x 156x                               156x 156x                                   165x   105x 105x 105x   56x 56x 56x   4x 4x   165x                                       28x 28x 28x 28x                                               28x 28x 28x   28x   28x 28x 26x   2x       28x                 28x 28x     28x                 28x                   28x                                           28x             84x 84x 84x 140x   84x     84x         84x                                                     28x 56x     28x             28x                                             81x   27x   27x       27x                             28x   27x       1x                                     28x 28x   81x 108x   81x 54x   81x                                     28x                                               613x                           1267x               1267x                           613x           613x                           722x         722x                     654x         654x                                       156x 109x 156x   621x 613x     613x                         156x                                                   156x 109x   156x 654x     156x   109x   654x 654x   109x                   156x                                                                                         159x   156x 156x     159x 159x 159x 159x   159x 28x 28x               28x 28x             28x 28x             28x 28x                   156x 156x 156x 156x 156x           156x           156x             156x           156x 156x           156x               156x                                 156x   156x            
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/DeepAnalysisContent
 * @description Pure functions for building the deep political analysis HTML
 * section using the "5W + Impact" framework. This section is injected into
 * every article type to provide parliament-intelligence-grade analysis.
 *
 * The framework covers:
 * - **What**: Core subject
 * - **Who**: Key actors (political groups, rapporteurs, MEPs, institutions)
 * - **When**: Timeline and key dates
 * - **Why**: Root causes and strategic motivations
 * - **Winners/Losers**: Stakeholder impact assessment
 * - **Impact**: Multi-perspective consequences (political, economic, social, legal, geopolitical)
 * - **Actions → Consequences**: Causal chains from decisions to outcomes
 * - **Mistakes**: Miscalculations and missed opportunities
 * - **Outlook**: Strategic forward look
 */
 
import { escapeHTML, isSafeURL } from '../utils/file-utils.js';
import { getLocalizedString, DEEP_ANALYSIS_STRINGS } from '../constants/languages.js';
import type {
  DeepAnalysis,
  DeepAnalysisStrings,
  StakeholderOutcome,
  ActionConsequence,
  PoliticalMistake,
  StakeholderPerspective,
  StakeholderOutcomeMatrix,
  AnalysisStakeholderType,
  EnhancedDeepAnalysis,
  ConfidenceLevel,
  ReasoningChain,
  ScenarioPlanning,
  AnalysisQualityMetadata,
} from '../types/index.js';
import { ALL_STAKEHOLDER_TYPES } from '../types/index.js';
 
// ─── Sub-section builders ────────────────────────────────────────────────────
 
/**
 * Build the "What" sub-section
 *
 * @param what - Description of what happened
 * @param heading - Localized heading
 * @param contentLang - Language of the content text (omit when same as display language)
 * @returns HTML string
 */
function buildWhatSection(what: string, heading: string, contentLang?: string): string {
  Iif (!what) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  return `
            <div class="analysis-what">
              <h3>${escapeHTML(heading)}</h3>
              <p${langAttr}>${escapeHTML(what)}</p>
            </div>`;
}
 
/**
 * Build the "Who" sub-section with key actors list
 *
 * @param who - Array of actor names/descriptions
 * @param heading - Localized heading
 * @param contentLang - Language of the content text (omit when same as display language)
 * @returns HTML string
 */
function buildWhoSection(who: readonly string[], heading: string, contentLang?: string): string {
  if (who.length === 0) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  const items = who.map((actor) => `<li>${escapeHTML(actor)}</li>`).join('\n                ');
  return `
            <div class="analysis-who">
              <h3>${escapeHTML(heading)}</h3>
              <ul class="actor-list"${langAttr}>
                ${items}
              </ul>
            </div>`;
}
 
/**
 * Build the "When" sub-section with timeline
 *
 * @param when - Array of date/milestone descriptions
 * @param heading - Localized heading
 * @param contentLang - Language of the content text (omit when same as display language)
 * @returns HTML string
 */
function buildWhenSection(when: readonly string[], heading: string, contentLang?: string): string {
  if (when.length === 0) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  const items = when
    .map((milestone) => `<li class="timeline-item">${escapeHTML(milestone)}</li>`)
    .join('\n                ');
  return `
            <div class="analysis-when">
              <h3>${escapeHTML(heading)}</h3>
              <ol class="timeline-list"${langAttr}>
                ${items}
              </ol>
            </div>`;
}
 
/**
 * Build the "Why" sub-section
 *
 * @param why - Root cause analysis text
 * @param heading - Localized heading
 * @param contentLang - Language of the content text (omit when same as display language)
 * @returns HTML string
 */
function buildWhySection(why: string, heading: string, contentLang?: string): string {
  Iif (!why) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  return `
            <div class="analysis-why">
              <h3>${escapeHTML(heading)}</h3>
              <p${langAttr}>${escapeHTML(why)}</p>
            </div>`;
}
 
/**
 * Map stakeholder outcome to CSS class
 *
 * @param outcome - Winner/loser/neutral
 * @returns CSS class name
 */
function outcomeClass(outcome: StakeholderOutcome['outcome']): string {
  return `stakeholder-${outcome}`;
}
 
/**
 * Get localized label for stakeholder outcome
 *
 * @param outcome - Winner/loser/neutral
 * @param strings - Localized strings
 * @param strings.winnerLabel - Label for winning stakeholders
 * @param strings.loserLabel - Label for losing stakeholders
 * @param strings.neutralLabel - Label for neutral stakeholders
 * @returns Localized label
 */
function outcomeLabel(
  outcome: StakeholderOutcome['outcome'],
  strings: { winnerLabel: string; loserLabel: string; neutralLabel: string }
): string {
  switch (outcome) {
    case 'winner':
      return strings.winnerLabel;
    case 'loser':
      return strings.loserLabel;
    default:
      return strings.neutralLabel;
  }
}
 
/**
 * Build the "Winners & Losers" sub-section
 *
 * @param outcomes - Stakeholder assessments
 * @param heading - Localized heading
 * @param strings - Localized label strings
 * @param strings.winnerLabel - Label for winning stakeholders
 * @param strings.loserLabel - Label for losing stakeholders
 * @param strings.neutralLabel - Label for neutral stakeholders
 * @param contentLang - Language of the actor/reason text (omit when same as display language)
 * @returns HTML string
 */
function buildStakeholderSection(
  outcomes: readonly StakeholderOutcome[],
  heading: string,
  strings: { winnerLabel: string; loserLabel: string; neutralLabel: string },
  contentLang?: string
): string {
  if (outcomes.length === 0) return '';
  const contentLangAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  const items = outcomes
    .map(
      (s) =>
        `<li class="stakeholder-item ${outcomeClass(s.outcome)}">` +
        `<span class="stakeholder-badge">${escapeHTML(outcomeLabel(s.outcome, strings))}</span> ` +
        `<span${contentLangAttr}><strong>${escapeHTML(s.actor)}</strong>: ${escapeHTML(s.reason)}</span>` +
        `</li>`
    )
    .join('\n                ');
  return `
            <div class="analysis-stakeholders">
              <h3>${escapeHTML(heading)}</h3>
              <ul class="stakeholder-list">
                ${items}
              </ul>
            </div>`;
}
 
/**
 * Build the multi-perspective "Impact Assessment" sub-section
 *
 * @param impact - Impact strings per perspective
 * @param heading - Localized heading
 * @param labels - Localized perspective labels
 * @param labels.politicalLabel - Label for political perspective
 * @param labels.economicLabel - Label for economic perspective
 * @param labels.socialLabel - Label for social perspective
 * @param labels.legalLabel - Label for legal perspective
 * @param labels.geopoliticalLabel - Label for geopolitical perspective
 * @param contentLang - Language of the content text (omit when same as display language)
 * @returns HTML string
 */
function buildImpactSection(
  impact: DeepAnalysis['impactAssessment'],
  heading: string,
  labels: {
    politicalLabel: string;
    economicLabel: string;
    socialLabel: string;
    legalLabel: string;
    geopoliticalLabel: string;
  },
  contentLang?: string
): string {
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  const perspectives = [
    { label: labels.politicalLabel, text: impact.political, css: 'impact-political' },
    { label: labels.economicLabel, text: impact.economic, css: 'impact-economic' },
    { label: labels.socialLabel, text: impact.social, css: 'impact-social' },
    { label: labels.legalLabel, text: impact.legal, css: 'impact-legal' },
    { label: labels.geopoliticalLabel, text: impact.geopolitical, css: 'impact-geopolitical' },
  ].filter((p) => p.text);
  if (perspectives.length === 0) return '';
  const items = perspectives
    .map(
      (p) =>
        `<div class="impact-card ${p.css}">` +
        `<h4>${escapeHTML(p.label)}</h4>` +
        `<p${langAttr}>${escapeHTML(p.text)}</p>` +
        `</div>`
    )
    .join('\n              ');
  return `
            <div class="analysis-impact">
              <h3>${escapeHTML(heading)}</h3>
              <div class="impact-grid">
              ${items}
              </div>
            </div>`;
}
 
/**
 * Get localized severity label
 *
 * @param severity - Severity level
 * @param strings - Localized strings
 * @param strings.severityLow - Label for low severity
 * @param strings.severityMedium - Label for medium severity
 * @param strings.severityHigh - Label for high severity
 * @param strings.severityCritical - Label for critical severity
 * @returns Localized label
 */
function severityLabel(
  severity: ActionConsequence['severity'],
  strings: {
    severityLow: string;
    severityMedium: string;
    severityHigh: string;
    severityCritical: string;
  }
): string {
  switch (severity) {
    case 'low':
      return strings.severityLow;
    case 'medium':
      return strings.severityMedium;
    case 'high':
      return strings.severityHigh;
    case 'critical':
      return strings.severityCritical;
    default:
      return String(severity);
  }
}
 
/**
 * Build the "Actions → Consequences" sub-section
 *
 * @param items - Action-consequence pairs
 * @param heading - Localized heading
 * @param labels - Localized column labels
 * @param labels.actionLabel - Column header for action
 * @param labels.consequenceLabel - Column header for consequence
 * @param labels.severityColumnLabel - Column header for severity
 * @param strings - Localized severity strings
 * @param strings.severityLow - Label for low severity
 * @param strings.severityMedium - Label for medium severity
 * @param strings.severityHigh - Label for high severity
 * @param strings.severityCritical - Label for critical severity
 * @param contentLang - Language of the content text (omit when same as display language)
 * @returns HTML string
 */
function buildConsequencesSection(
  items: readonly ActionConsequence[],
  heading: string,
  labels: Readonly<
    Pick<DeepAnalysisStrings, 'actionLabel' | 'consequenceLabel' | 'severityColumnLabel'>
  >,
  strings: {
    severityLow: string;
    severityMedium: string;
    severityHigh: string;
    severityCritical: string;
  },
  contentLang?: string
): string {
  if (items.length === 0) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  const rows = items
    .map(
      (item) =>
        `<tr class="consequence-row severity-${escapeHTML(item.severity)}">` +
        `<td class="action-cell"${langAttr}>${escapeHTML(item.action)}</td>` +
        `<td class="arrow-cell">→</td>` +
        `<td class="consequence-cell"${langAttr}>${escapeHTML(item.consequence)}</td>` +
        `<td class="severity-cell"><span class="severity-badge severity-${escapeHTML(item.severity)}">${escapeHTML(severityLabel(item.severity, strings))}</span></td>` +
        `</tr>`
    )
    .join('\n                ');
  return `
            <div class="analysis-consequences">
              <h3>${escapeHTML(heading)}</h3>
              <table class="consequences-table" role="table">
                <thead>
                  <tr>
                    <th scope="col">${escapeHTML(labels.actionLabel)}</th>
                    <th scope="col" aria-hidden="true"></th>
                    <th scope="col">${escapeHTML(labels.consequenceLabel)}</th>
                    <th scope="col">${escapeHTML(labels.severityColumnLabel)}</th>
                  </tr>
                </thead>
                <tbody>
                ${rows}
                </tbody>
              </table>
            </div>`;
}
 
/**
 * Build the "Mistakes" sub-section
 *
 * @param mistakes - Political mistake assessments
 * @param heading - Localized heading
 * @param alternativeLabel - Localized "should have" label
 * @param contentLang - Language of the description/alternative text (omit when same as display language)
 * @returns HTML string
 */
function buildMistakesSection(
  mistakes: readonly PoliticalMistake[],
  heading: string,
  alternativeLabel: string,
  contentLang?: string
): string {
  if (mistakes.length === 0) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  const items = mistakes
    .map(
      (m) =>
        `<div class="mistake-card">` +
        `<p class="mistake-actor"><strong>${escapeHTML(m.actor)}</strong></p>` +
        `<p class="mistake-description"${langAttr}>${escapeHTML(m.description)}</p>` +
        `<p class="mistake-alternative"><em>${escapeHTML(alternativeLabel)}:</em> <span${langAttr}>${escapeHTML(m.alternative)}</span></p>` +
        `</div>`
    )
    .join('\n              ');
  return `
            <div class="analysis-mistakes">
              <h3>${escapeHTML(heading)}</h3>
              ${items}
            </div>`;
}
 
/**
 * Build the "Strategic Outlook" sub-section
 *
 * @param outlook - Forward-looking analysis text
 * @param heading - Localized heading
 * @param contentLang - Language of the content text (omit when same as display language)
 * @returns HTML string
 */
function buildOutlookSection(outlook: string, heading: string, contentLang?: string): string {
  if (!outlook) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  return `
            <div class="analysis-outlook">
              <h3>${escapeHTML(heading)}</h3>
              <p${langAttr}>${escapeHTML(outlook)}</p>
            </div>`;
}
 
// ─── Enhanced analysis section builders ──────────────────────────────────────
 
/**
 * Type guard — checks whether an analysis object carries enhanced fields
 *
 * @param a - Base deep analysis to test
 * @returns `true` when the object is an `EnhancedDeepAnalysis`
 */
function isEnhancedDeepAnalysis(a: DeepAnalysis): a is EnhancedDeepAnalysis {
  Iif (typeof a !== 'object' || a === null) return false;
  return (
    'qualityMetadata' in a ||
    'scenarioPlanning' in a ||
    'reasoningChains' in a ||
    'executiveSummary' in a
  );
}
 
/**
 * Build a confidence badge with emoji indicator and text label
 *
 * @param confidence - Confidence level
 * @param strings - Localized strings
 * @returns HTML span element
 */
function buildConfidenceBadge(confidence: ConfidenceLevel, strings: DeepAnalysisStrings): string {
  let emoji: string;
  let label: string;
  switch (confidence) {
    case 'high':
      emoji = '🟢';
      label = strings.confidenceHigh;
      break;
    case 'medium':
      emoji = '🟡';
      label = strings.confidenceMedium;
      break;
    default:
      emoji = '🔴';
      label = strings.confidenceLow;
  }
  return `<span class="confidence-badge confidence-${escapeHTML(confidence)}" aria-label="${escapeHTML(label)}">${emoji} ${escapeHTML(label)}</span>`;
}
 
/**
 * Build the executive summary section
 *
 * @param summary - Executive summary text
 * @param confidence - Optional overall confidence level
 * @param heading - Localized heading
 * @param strings - Localized strings
 * @param contentLang - Language of the content text
 * @returns HTML string
 */
function buildExecutiveSummarySection(
  summary: string,
  confidence: ConfidenceLevel | undefined,
  heading: string,
  strings: DeepAnalysisStrings,
  contentLang?: string
): string {
  Iif (!summary) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  const badge = confidence ? buildConfidenceBadge(confidence, strings) : '';
  return `
            <div class="analysis-executive-summary">
              <h3>${escapeHTML(heading)}</h3>
              <div class="summary-header">
                <p${langAttr}>${escapeHTML(summary)}</p>${badge}
              </div>
            </div>`;
}
 
/**
 * Build the reasoning chains section
 *
 * @param chains - Reasoning chain items
 * @param heading - Localized heading
 * @param strings - Localized strings
 * @param contentLang - Language of the content text
 * @returns HTML string
 */
function buildReasoningChainSection(
  chains: readonly ReasoningChain[],
  heading: string,
  strings: DeepAnalysisStrings,
  contentLang?: string
): string {
  Iif (chains.length === 0) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  const cards = chains
    .map((chain) => {
      const evidenceItems = chain.evidence
        .map((ref) => {
          const dateText = ref.date ? ` (${escapeHTML(ref.date)})` : '';
          if (ref.url && isSafeURL(ref.url)) {
            return `<li${langAttr}><a href="${escapeHTML(ref.url)}" target="_blank" rel="noopener noreferrer">${escapeHTML(ref.title)}${dateText}</a></li>`;
          }
          return `<li${langAttr}>${escapeHTML(ref.title)}${dateText}</li>`;
        })
        .join('\n                  ');
      const evidenceHtml =
        chain.evidence.length > 0
          ? `<div class="evidence-refs-block">
                  <h4>${escapeHTML(strings.evidenceRefsHeading)}</h4>
                  <ul class="evidence-refs">
                  ${evidenceItems}
                  </ul>
                </div>`
          : '';
 
      const counterItems = chain.counterArguments
        .map((ca) => `<li${langAttr}>${escapeHTML(ca)}</li>`)
        .join('\n                  ');
      const counterHtml =
        chain.counterArguments.length > 0
          ? `<div class="counter-args-block">
                  <h4>${escapeHTML(strings.counterArgumentsHeading)}</h4>
                  <ul class="counter-arguments">
                  ${counterItems}
                  </ul>
                </div>`
          : '';
 
      return `<div class="reasoning-chain-card">
                <p><strong>${escapeHTML(strings.premiseLabel)}</strong> <span${langAttr}>${escapeHTML(chain.premise)}</span></p>
                ${evidenceHtml}
                <p><strong>${escapeHTML(strings.inferenceLabel)}</strong> <span${langAttr}>${escapeHTML(chain.inference)}</span></p>
                ${buildConfidenceBadge(chain.confidence, strings)}
                ${counterHtml}
                <p class="chain-conclusion"><strong>${escapeHTML(strings.conclusionLabel)}</strong> <span${langAttr}>${escapeHTML(chain.conclusion)}</span></p>
              </div>`;
    })
    .join('\n              ');
  return `
            <div class="analysis-reasoning-chains">
              <h3>${escapeHTML(heading)}</h3>
              ${cards}
            </div>`;
}
 
/**
 * Build the scenario planning section
 *
 * @param scenarios - Scenario planning data
 * @param heading - Localized heading
 * @param strings - Localized strings
 * @param contentLang - Language of the content text
 * @returns HTML string
 */
function buildScenarioPlanningSection(
  scenarios: ScenarioPlanning,
  heading: string,
  strings: DeepAnalysisStrings,
  contentLang?: string
): string {
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
 
  function renderScenario(
    scenario: ScenarioPlanning['bestCase'],
    cssClass: string,
    label: string
  ): string {
    const rawPct = Number.isFinite(scenario.probability) ? scenario.probability * 100 : 0;
    const pct = Math.max(0, Math.min(100, Math.round(rawPct)));
    const triggerItems = scenario.triggers
      .map((t) => `<li${langAttr}>${escapeHTML(t)}</li>`)
      .join('\n                  ');
    const impactItems = scenario.implications
      .map(
        (imp) =>
          `<li class="scenario-impact scenario-severity-${escapeHTML(imp.severity)}">` +
          `<strong>${escapeHTML(imp.stakeholder)}</strong>: <span${langAttr}>${escapeHTML(imp.impact)}</span>` +
          `</li>`
      )
      .join('\n                  ');
    return `<div class="scenario-card ${escapeHTML(cssClass)}">
                <h4>${escapeHTML(label)}</h4>
                <p${langAttr}>${escapeHTML(scenario.description)}</p>
                <div class="scenario-probability">
                  <span>${escapeHTML(strings.probabilityLabel)}: ${pct}%</span>
                  <div class="probability-bar" style="width:${pct}%" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100" aria-label="${escapeHTML(label)} ${pct}%"></div>
                </div>
                ${
                  scenario.triggers.length > 0
                    ? `<details class="scenario-triggers">
                  <summary>${escapeHTML(strings.triggersLabel)}</summary>
                  <ul>${triggerItems}</ul>
                </details>`
                    : ''
                }
                ${
                  scenario.implications.length > 0
                    ? `<details class="scenario-impacts">
                  <summary>${escapeHTML(strings.impliedImpactsLabel)}</summary>
                  <ul class="scenario-impact-list">${impactItems}</ul>
                </details>`
                    : ''
                }
                <p class="scenario-timeline"><strong>${escapeHTML(strings.timelineLabel)}:</strong> <span${langAttr}>${escapeHTML(scenario.timeline)}</span></p>
              </div>`;
  }
 
  const wildcardItems = scenarios.wildcards
    .map((w) => `<li${langAttr}>${escapeHTML(w)}</li>`)
    .join('\n              ');
  const wildcardHtml =
    scenarios.wildcards.length > 0
      ? `<div class="scenario-wildcards">
              <h4>${escapeHTML(strings.wildcardsLabel)}</h4>
              <ul class="wildcard-list">${wildcardItems}</ul>
            </div>`
      : '';
 
  return `
            <div class="analysis-scenario-planning">
              <h3>${escapeHTML(heading)}</h3>
              <div class="scenario-grid">
                ${renderScenario(scenarios.bestCase, 'scenario-best', strings.bestCaseLabel)}
                ${renderScenario(scenarios.mostLikely, 'scenario-likely', strings.mostLikelyLabel)}
                ${renderScenario(scenarios.worstCase, 'scenario-worst', strings.worstCaseLabel)}
              </div>
              ${wildcardHtml}
            </div>`;
}
 
/**
 * Map iteration type to localized label
 *
 * @param type - Iteration type
 * @param strings - Localized strings
 * @returns Localized label
 */
function iterationTypeLabel(
  type: 'initial' | 'stakeholder_challenge' | 'evidence_validation' | 'synthesis',
  strings: DeepAnalysisStrings
): string {
  switch (type) {
    case 'initial':
      return strings.iterationInitial;
    case 'stakeholder_challenge':
      return strings.iterationStakeholderChallenge;
    case 'evidence_validation':
      return strings.iterationEvidenceValidation;
    default:
      return strings.iterationSynthesis;
  }
}
 
/**
 * Map evidence strength to localized label
 *
 * @param strength - Evidence strength
 * @param strings - Localized strings
 * @returns Localized label
 */
function evidenceStrengthLabel(
  strength: 'strong' | 'moderate' | 'weak',
  strings: DeepAnalysisStrings
): string {
  switch (strength) {
    case 'strong':
      return strings.evidenceStrong;
    case 'moderate':
      return strings.evidenceModerate;
    default:
      return strings.evidenceWeak;
  }
}
 
/**
 * Build the analysis methodology section
 *
 * @param metadata - Quality metadata
 * @param heading - Localized heading
 * @param strings - Localized strings
 * @param contentLang - Language of the content text
 * @returns HTML string
 */
function buildAnalysisMethodologySection(
  metadata: AnalysisQualityMetadata,
  heading: string,
  strings: DeepAnalysisStrings,
  contentLang?: string
): string {
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  const iterationItems = metadata.iterations
    .map((iter) => {
      const findingItems = iter.findings
        .map((f) => `<li${langAttr}>${escapeHTML(f)}</li>`)
        .join('\n                  ');
      const refinementItems = iter.refinements
        .map((r) => `<li${langAttr}>${escapeHTML(r)}</li>`)
        .join('\n                  ');
      return `<div class="iteration-item">
                <div class="iteration-header">
                  <span class="iteration-pass">Pass ${escapeHTML(String(Number.isFinite(iter.pass) ? iter.pass : 0))}</span>
                  <span class="iteration-type">${escapeHTML(iterationTypeLabel(iter.type, strings))}</span>
                  ${buildConfidenceBadge(iter.confidence, strings)}
                </div>
                ${
                  iter.findings.length > 0
                    ? `<ul class="iteration-findings">${findingItems}</ul>`
                    : ''
                }
                ${
                  iter.refinements.length > 0
                    ? `<ul class="iteration-refinements">${refinementItems}</ul>`
                    : ''
                }
              </div>`;
    })
    .join('\n              ');
  return `
            <div class="analysis-methodology">
              <h3>${escapeHTML(heading)}</h3>
              <dl class="methodology-stats">
                <dt>${escapeHTML(strings.overallConfidenceLabel)}</dt>
                <dd>${buildConfidenceBadge(metadata.overallConfidence, strings)}</dd>
                <dt>${escapeHTML(strings.evidenceStrengthLabel)}</dt>
                <dd>${escapeHTML(evidenceStrengthLabel(metadata.evidenceStrength, strings))}</dd>
                <dt>${escapeHTML(strings.iterationCountLabel)}</dt>
                <dd>${escapeHTML(String(Number.isFinite(metadata.iterationCount) ? metadata.iterationCount : 0))}</dd>
              </dl>
              ${metadata.iterations.length > 0 ? `<div class="iteration-timeline">${iterationItems}</div>` : ''}
            </div>`;
}
 
// ─── Main builder ────────────────────────────────────────────────────────────
 
/**
 * Map a StakeholderPerspective impact to a CSS class suffix.
 *
 * @param impact - Stakeholder impact direction
 * @returns CSS class suffix
 */
function perspectiveImpactClass(impact: StakeholderPerspective['impact']): string {
  return `perspective-${impact}`;
}
 
/**
 * Map a stakeholder type to its localized display label.
 *
 * @param stakeholder - Internal stakeholder type identifier
 * @param strings - Localized label strings
 * @returns Localized stakeholder label
 */
function localizedStakeholderLabel(
  stakeholder: AnalysisStakeholderType,
  strings: DeepAnalysisStrings
): string {
  const map: Record<AnalysisStakeholderType, string> = {
    political_groups: strings.politicalGroupsLabel,
    civil_society: strings.civilSocietyLabel,
    industry: strings.industryLabel,
    national_govts: strings.nationalGovtsLabel,
    citizens: strings.citizensLabel,
    eu_institutions: strings.euInstitutionsLabel,
  };
  return map[stakeholder];
}
 
/**
 * Map a stakeholder impact direction to its localized display label.
 *
 * @param impact - Impact direction value
 * @param strings - Localized label strings
 * @returns Localized impact label
 */
function localizedImpactLabel(
  impact: StakeholderPerspective['impact'],
  strings: DeepAnalysisStrings
): string {
  const map: Record<StakeholderPerspective['impact'], string> = {
    positive: strings.positiveLabel,
    negative: strings.negativeLabel,
    neutral: strings.neutralLabel,
    mixed: strings.mixedLabel,
  };
  return map[impact];
}
 
/**
 * Map a severity level to its localized display label.
 *
 * @param severity - Severity level value
 * @param strings - Localized label strings
 * @returns Localized severity label
 */
function localizedSeverityLabel(
  severity: StakeholderPerspective['severity'],
  strings: DeepAnalysisStrings
): string {
  const map: Record<StakeholderPerspective['severity'], string> = {
    high: strings.severityHigh,
    medium: strings.severityMedium,
    low: strings.severityLow,
  };
  return map[severity];
}
 
/**
 * Map an outcome value to its localized display label.
 *
 * @param outcome - Outcome value (winner/loser/neutral)
 * @param strings - Localized label strings
 * @returns Localized outcome label
 */
function localizedOutcomeLabel(outcome: string, strings: DeepAnalysisStrings): string {
  const map: Record<string, string> = {
    winner: strings.winnerLabel,
    loser: strings.loserLabel,
    neutral: strings.neutralLabel,
  };
  return map[outcome] ?? outcome;
}
 
/**
 * Build the "Multi-Stakeholder Perspectives" sub-section.
 * Renders a card grid with one card per stakeholder group showing
 * impact direction, severity, reasoning, and evidence.
 *
 * @param perspectives - Array of stakeholder perspectives
 * @param heading - Localized section heading
 * @param strings - Localized label strings for stakeholder names, impact, and severity
 * @param contentLang - Language of the reasoning/evidence text
 * @returns HTML string, or empty string if no perspectives provided
 */
function buildStakeholderPerspectivesSection(
  perspectives: readonly StakeholderPerspective[] | undefined,
  heading: string,
  strings: DeepAnalysisStrings,
  contentLang?: string
): string {
  if (!perspectives || perspectives.length === 0) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
  const cards = perspectives
    .map((p) => {
      const evidenceItems = p.evidence.map((e) => `<li>${escapeHTML(e)}</li>`).join('');
      const evidenceHtml = evidenceItems
        ? `<ul class="perspective-evidence">${evidenceItems}</ul>`
        : '';
      return (
        `<div class="stakeholder-perspective-card ${escapeHTML(perspectiveImpactClass(p.impact))} severity-${escapeHTML(p.severity)}">` +
        `<div class="perspective-header">` +
        `<span class="perspective-stakeholder">${escapeHTML(localizedStakeholderLabel(p.stakeholder, strings))}</span>` +
        `<span class="perspective-impact-badge perspective-impact-${escapeHTML(p.impact)}">${escapeHTML(localizedImpactLabel(p.impact, strings))}</span>` +
        `<span class="perspective-severity-badge severity-${escapeHTML(p.severity)}">${escapeHTML(localizedSeverityLabel(p.severity, strings))}</span>` +
        `</div>` +
        `<p class="perspective-reasoning"${langAttr}>${escapeHTML(p.reasoning)}</p>` +
        evidenceHtml +
        `</div>`
      );
    })
    .join('\n              ');
  return `
            <div class="analysis-stakeholder-perspectives">
              <h3>${escapeHTML(heading)}</h3>
              <div class="stakeholder-perspectives-grid">
              ${cards}
              </div>
            </div>`;
}
 
/**
 * Build the "Stakeholder Outcome Matrix" sub-section.
 * Renders an accessible table mapping each action to winner/loser/neutral
 * outcomes per stakeholder group.
 *
 * @param matrix - Array of stakeholder outcome matrix rows
 * @param heading - Localized section heading
 * @param strings - Localized label strings for columns and stakeholder groups
 * @param contentLang - Language of the action text
 * @returns HTML string, or empty string if no matrix rows provided
 */
function buildStakeholderOutcomeMatrixSection(
  matrix: readonly StakeholderOutcomeMatrix[] | undefined,
  heading: string,
  strings: DeepAnalysisStrings,
  contentLang?: string
): string {
  if (!matrix || matrix.length === 0) return '';
  const langAttr = contentLang ? ` lang="${escapeHTML(contentLang)}"` : '';
 
  const headerCells = ALL_STAKEHOLDER_TYPES.map(
    (s) => `<th scope="col">${escapeHTML(localizedStakeholderLabel(s, strings))}</th>`
  ).join('');
 
  const rows = matrix
    .map((row) => {
      const cells = ALL_STAKEHOLDER_TYPES.map((s) => {
        // eslint-disable-next-line security/detect-object-injection -- key from const array
        const outcome = row.outcomes[s];
        return `<td class="matrix-cell outcome-${escapeHTML(outcome)}">${escapeHTML(localizedOutcomeLabel(outcome, strings))}</td>`;
      }).join('');
      return (
        `<tr>` +
        `<th scope="row" class="matrix-action"${langAttr}>${escapeHTML(row.action)}</th>` +
        `<td class="matrix-confidence confidence-${escapeHTML(row.confidence)}">${escapeHTML(localizedSeverityLabel(row.confidence, strings))}</td>` +
        cells +
        `</tr>`
      );
    })
    .join('\n                ');
 
  return `
            <div class="analysis-outcome-matrix">
              <h3>${escapeHTML(heading)}</h3>
              <div class="outcome-matrix-scroll">
              <table class="outcome-matrix-table" role="table">
                <thead>
                  <tr>
                    <th scope="col">${escapeHTML(strings.actionLabel)}</th>
                    <th scope="col">${escapeHTML(strings.confidenceLabel)}</th>
                    ${headerCells}
                  </tr>
                </thead>
                <tbody>
                ${rows}
                </tbody>
              </table>
              </div>
            </div>`;
}
 
/**
 * Build the complete deep political analysis section HTML.
 *
 * This section provides parliament-intelligence-grade analysis using the
 * "5W + Impact" framework. When the input is an `EnhancedDeepAnalysis` it
 * additionally renders an executive summary, reasoning chains, scenario
 * planning, and analysis methodology.
 *
 * Returns an empty string if the analysis object is null/undefined or
 * contains no meaningful content.
 *
 * @param analysis - Deep analysis data (null/undefined returns empty string).
 *   Accepts both `DeepAnalysis` and `EnhancedDeepAnalysis`.
 * @param lang - BCP 47 language code for localized headings
 * @param contentLang - BCP 47 language code for the content text; when it
 *   differs from `lang`, each content element gets a `lang` attribute so
 *   screen readers and translation tools handle the language switch correctly.
 *   Defaults to `lang` (no extra attributes added).
 * @returns HTML section string or empty string
 */
export function buildDeepAnalysisSection(
  analysis: DeepAnalysis | EnhancedDeepAnalysis | null | undefined,
  lang: string,
  contentLang = lang
): string {
  if (!analysis) return '';
 
  const strings = getLocalizedString(DEEP_ANALYSIS_STRINGS, lang);
  const cl = contentLang !== lang ? contentLang : undefined;
 
  // ─── Enhanced sections (before/after base sections) ────────────────────
  let executiveSummaryHtml = '';
  let reasoningChainsHtml = '';
  let scenarioPlanningHtml = '';
  let methodologyHtml = '';
 
  if (isEnhancedDeepAnalysis(analysis)) {
    Eif (analysis.executiveSummary) {
      executiveSummaryHtml = buildExecutiveSummarySection(
        analysis.executiveSummary,
        analysis.qualityMetadata?.overallConfidence,
        strings.executiveSummaryHeading,
        strings,
        cl
      );
    }
    Eif (analysis.reasoningChains && analysis.reasoningChains.length > 0) {
      reasoningChainsHtml = buildReasoningChainSection(
        analysis.reasoningChains,
        strings.reasoningChainsHeading,
        strings,
        cl
      );
    }
    Eif (analysis.scenarioPlanning) {
      scenarioPlanningHtml = buildScenarioPlanningSection(
        analysis.scenarioPlanning,
        strings.scenarioPlanningHeading,
        strings,
        cl
      );
    }
    Eif (analysis.qualityMetadata) {
      methodologyHtml = buildAnalysisMethodologySection(
        analysis.qualityMetadata,
        strings.analysisMethodologyHeading,
        strings,
        cl
      );
    }
  }
 
  // ─── Base "5W + Impact" sections ───────────────────────────────────────
  const whatHtml = buildWhatSection(analysis.what, strings.whatHeading, cl);
  const whoHtml = buildWhoSection(analysis.who, strings.whoHeading, cl);
  const whenHtml = buildWhenSection(analysis.when, strings.whenHeading, cl);
  const whyHtml = buildWhySection(analysis.why, strings.whyHeading, cl);
  const stakeholderHtml = buildStakeholderSection(
    analysis.stakeholderOutcomes,
    strings.stakeholderHeading,
    strings,
    cl
  );
  const impactHtml = buildImpactSection(
    analysis.impactAssessment,
    strings.impactHeading,
    strings,
    cl
  );
  const consequencesHtml = buildConsequencesSection(
    analysis.actionConsequences,
    strings.consequencesHeading,
    strings,
    strings,
    cl
  );
  const mistakesHtml = buildMistakesSection(
    analysis.mistakes,
    strings.mistakesHeading,
    strings.alternativeLabel,
    cl
  );
  const outlookHtml = buildOutlookSection(analysis.outlook, strings.outlookHeading, cl);
  const perspectivesHtml = buildStakeholderPerspectivesSection(
    analysis.stakeholderPerspectives,
    strings.perspectivesHeading,
    strings,
    cl
  );
  const outcomeMatrixHtml = buildStakeholderOutcomeMatrixSection(
    analysis.stakeholderOutcomeMatrix,
    strings.outcomeMatrixHeading,
    strings,
    cl
  );
 
  const innerContent =
    executiveSummaryHtml +
    whatHtml +
    whoHtml +
    whenHtml +
    whyHtml +
    reasoningChainsHtml +
    stakeholderHtml +
    impactHtml +
    consequencesHtml +
    mistakesHtml +
    outlookHtml +
    scenarioPlanningHtml +
    perspectivesHtml +
    outcomeMatrixHtml +
    methodologyHtml;
 
  // If all sub-sections are empty, return nothing
  Iif (!innerContent.trim()) return '';
 
  return `
          <section class="deep-analysis" lang="${escapeHTML(lang)}">
            <h2>${escapeHTML(strings.sectionHeading)}</h2>
            ${innerContent}
          </section>`;
}