All files / scripts/ai-analysis pipeline.ts

5.35% Statements 29/542
0% Branches 0/437
0% Functions 0/219
6% Lines 29/483

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 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638                                                                                                            10x                     10x                 10x                 10x                         10x             10x                                           10x                   10x                                   10x                   10x                                   10x                   10x                                   10x                   10x                                   10x                   10x                                   10x                   10x                         10x                 10x                                         10x                 10x                 10x                 10x                 10x                                 10x                                 10x                                                                                                                                                                                                                                                                                                                                                                                                                                                                           10x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       10x                                                                                              
/**
 * @module ai-analysis/pipeline
 * @description AI-first analysis pipeline for deep-inspection articles.
 *
 * Implements the `AnalysisPipeline` interface with a content-driven approach:
 *   - Iteration 1 (`analyzeDocuments`): document classification, policy domain
 *     detection, stakeholder mapping, and evidence-based SWOT skeleton.
 *   - Iteration 2 (`refineAnalysis`): enrich SWOT entries from full-text content
 *     when documents are enriched; replace generic placeholders with specific
 *     claims drawn from actual document passages.
 *   - Iteration 3 (`validateCompleteness`): assess stakeholder coverage, policy
 *     domain confidence, and watch-point quality. Reports gap scores.
 *
 * Primary analysis text is content-derived from document metadata, passages, and
 * policy domain analysis. Fallback placeholder sentences (`buildPlaceholderText`)
 * are used only when a stakeholder ร— quadrant combination has zero matching
 * documents; they are never on the critical path for document-rich analyses.
 *
 * The implementation is designed as a drop-in target for future LLM API
 * integration: replace the content-extraction helpers (and fallback placeholders)
 * with API calls.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import type { Language } from '../types/language.js';
import type { RawDocument } from '../data-transformers/types.js';
import {
  detectPolicyDomains,
  getDomainSpecificAnalysis,
  detectNarrativeFrames,
  assessConfidenceLevel,
} from '../data-transformers/policy-analysis.js';
import { extractKeyPassage, cleanMotionText, isPersonProfileText } from '../data-transformers/helpers.js';
import { localizeDocType } from '../data-transformers/content-generators/index.js';
 
import type {
  AnalysisPipeline,
  AnalysisPipelineOptions,
  AnalysisResult,
  AnalysisStakeholderSwot,
  AnalysisSwotEntry,
  AnalysisWatchPoint,
  AnalysisMindmapBranch,
  PolicyAssessment,
  DashboardData,
  ValidationResult,
} from './types.js';
 
// ---------------------------------------------------------------------------
// Palette for dashboard type distribution charts
// ---------------------------------------------------------------------------
 
const TYPE_PALETTE: readonly string[] = [
  '#00d9ff', '#ff006e', '#ffbe0b', '#7b2fff', '#00c58e',
  '#ff6b35', '#4dd0e1', '#f48fb1', '#a5d6a7', '#ce93d8',
];
 
// ---------------------------------------------------------------------------
// Localised stakeholder names (14 languages)
// ---------------------------------------------------------------------------
 
type LangRecord = Partial<Record<Language, string>>;
 
const GOV_NAMES: LangRecord = {
  en: 'Government / Policy Administration', sv: 'Regering / Policyfรถrvaltning',
  da: 'Regering / Politisk forvaltning', no: 'Regjering / Politisk forvaltning',
  fi: 'Hallitus / Poliittinen hallinto', de: 'Regierung / Politikverwaltung',
  fr: 'Gouvernement / Administration', es: 'Gobierno / Administraciรณn pรบblica',
  nl: 'Regering / Beleidsadministratie', ar: 'ุงู„ุญูƒูˆู…ุฉ / ุงู„ุฅุฏุงุฑุฉ ุงู„ุณูŠุงุณูŠุฉ',
  he: 'ืžืžืฉืœื” / ืžื™ื ื”ืœ ืžื“ื™ื ื™ื•ืช', ja: 'ๆ”ฟๅบœ / ๆ”ฟ็ญ–่กŒๆ”ฟ', ko: '์ •๋ถ€ / ์ •์ฑ… ํ–‰์ •', zh: 'ๆ”ฟๅบœ / ๆ”ฟ็ญ–็ฎก็†',
};
 
const OPP_NAMES: LangRecord = {
  en: 'Parliament / Opposition', sv: 'Riksdag / Opposition',
  da: 'Folketing / Opposition', no: 'Storting / Opposisjon',
  fi: 'Eduskunta / Oppositio', de: 'Parlament / Opposition',
  fr: 'Parlement / Opposition', es: 'Parlamento / Oposiciรณn',
  nl: 'Parlement / Oppositie', ar: 'ุงู„ุจุฑู„ู…ุงู† / ุงู„ู…ุนุงุฑุถุฉ',
  he: 'ืคืจืœืžื ื˜ / ืื•ืคื•ื–ื™ืฆื™ื”', ja: '่ญฐไผš / ้‡Žๅ…š', ko: '์˜ํšŒ / ์•ผ๋‹น', zh: '่ฎฎไผš / ๅๅฏนๆดพ',
};
 
const PRIVATE_NAMES: LangRecord = {
  en: 'Private Sector / Civil Society', sv: 'Privat sektor / Civilsamhรคlle',
  da: 'Privat sektor / Civilsamfund', no: 'Privat sektor / Sivilsamfunn',
  fi: 'Yksityissektori / Kansalaisyhteiskunta', de: 'Privatsektor / Zivilgesellschaft',
  fr: 'Secteur privรฉ / Sociรฉtรฉ civile', es: 'Sector privado / Sociedad civil',
  nl: 'Privรฉsector / Maatschappelijk middenveld', ar: 'ุงู„ู‚ุทุงุน ุงู„ุฎุงุต / ุงู„ู…ุฌุชู…ุน ุงู„ู…ุฏู†ูŠ',
  he: 'ื”ืžื’ื–ืจ ื”ืคืจื˜ื™ / ื”ื—ื‘ืจื” ื”ืื–ืจื—ื™ืช', ja: 'ๆฐ‘้–“ใ‚ปใ‚ฏใ‚ฟใƒผ / ๅธ‚ๆฐ‘็คพไผš', ko: '๋ฏผ๊ฐ„ ๋ถ€๋ฌธ / ์‹œ๋ฏผ ์‚ฌํšŒ', zh: '็ง่ฅ้ƒจ้—จ / ๆฐ‘้—ด็คพไผš',
};
 
// ---------------------------------------------------------------------------
// Data source labels (14 languages)
// ---------------------------------------------------------------------------
 
const DATA_SOURCE_LABELS: LangRecord = {
  en: 'Data Sources', sv: 'Datakรคllor', da: 'Datakilder', no: 'Datakilder',
  fi: 'Tietolรคhteet', de: 'Datenquellen', fr: 'Sources de donnรฉes', es: 'Fuentes de datos',
  nl: 'Gegevensbronnen', ar: 'ู…ุตุงุฏุฑ ุงู„ุจูŠุงู†ุงุช', he: 'ืžืงื•ืจื•ืช ื ืชื•ื ื™ื',
  ja: 'ใƒ‡ใƒผใ‚ฟใ‚ฝใƒผใ‚น', ko: '๋ฐ์ดํ„ฐ ์ถœ์ฒ˜', zh: 'ๆ•ฐๆฎๆฅๆบ',
};
 
const DATA_SOURCE_ITEMS: Partial<Record<Language, string[]>> = {
  en: ['Riksdag MCP (laws, motions, propositions)', 'World Bank (economic indicators)', 'SCB Statistics Sweden'],
  sv: ['Riksdagens MCP (lagar, motioner, propositioner)', 'Vรคrldsbanken (ekonomiska indikatorer)', 'SCB Statistikmyndigheten'],
  da: ['Riksdag MCP (love, motioner, forslag)', 'Verdensbanken (รธkonomiske indikatorer)', 'SCB Statistikmyndigheten'],
  no: ['Riksdag MCP (lover, motioner, proposisjoner)', 'Verdensbanken (รธkonomiske indikatorer)', 'SCB Statistikmyndigheten'],
  fi: ['Riksdagin MCP (lait, kirjelmรคt, esitykset)', 'Maailmanpankki (taloudelliset indikaattorit)', 'SCB Tilastoviranomainen'],
  de: ['Riksdag MCP (Gesetze, Antrรคge, Vorlagen)', 'Weltbank (Wirtschaftsindikatoren)', 'SCB Statistikmyndigheten'],
  fr: ['Riksdag MCP (lois, motions, propositions)', 'Banque mondiale (indicateurs รฉconomiques)', 'SCB Statistikmyndigheten'],
  es: ['Riksdag MCP (leyes, mociones, proposiciones)', 'Banco Mundial (indicadores econรณmicos)', 'SCB Statistikmyndigheten'],
  nl: ['Riksdag MCP (wetten, moties, voorstellen)', 'Wereldbank (economische indicatoren)', 'SCB Statistikmyndigheten'],
  ar: ['ุฑูŠูƒุณุฏุงุบ MCP (ู‚ูˆุงู†ูŠู†ุŒ ุงู‚ุชุฑุงุญุงุช)', 'ุงู„ุจู†ูƒ ุงู„ุฏูˆู„ูŠ (ู…ุคุดุฑุงุช ุงู‚ุชุตุงุฏูŠุฉ)', 'SCB ุฅุญุตุงุก ุงู„ุณูˆูŠุฏ'],
  he: ['ืจื™ืงืกื“ืื’ MCP (ื—ื•ืงื™ื, ื”ืฆืขื•ืช)', 'ื”ื‘ื ืง ื”ืขื•ืœืžื™ (ืื™ื ื“ื™ืงื˜ื•ืจื™ื ื›ืœื›ืœื™ื™ื)', 'SCB ื”ืœืฉื›ื” ื”ืžืจื›ื–ื™ืช ืœืกื˜ื˜ื™ืกื˜ื™ืงื”'],
  ja: ['Riksdag MCP (ๆณ•ๅพ‹ใƒปๅ‹•่ญฐใƒปๆๆกˆ)', 'ไธ–็•Œ้Š€่กŒ๏ผˆ็ตŒๆธˆๆŒ‡ๆจ™๏ผ‰', 'SCB ใ‚นใ‚ฆใ‚งใƒผใƒ‡ใƒณ็ตฑ่จˆๅฑ€'],
  ko: ['Riksdag MCP (๋ฒ•๋ฅ , ๋™์˜, ์ œ์•ˆ)', '์„ธ๊ณ„์€ํ–‰ (๊ฒฝ์ œ ์ง€ํ‘œ)', 'SCB ์Šค์›จ๋ด ํ†ต๊ณ„์ฒญ'],
  zh: ['่ฎฎไผš MCP๏ผˆๆณ•ๅพ‹ใ€ๅŠจ่ฎฎใ€ๆๆกˆ๏ผ‰', 'ไธ–็•Œ้“ถ่กŒ๏ผˆ็ปๆตŽๆŒ‡ๆ ‡๏ผ‰', 'SCB ็‘žๅ…ธ็ปŸ่ฎกๅฑ€'],
};
 
// ---------------------------------------------------------------------------
// Watch point labels (14 languages)
// ---------------------------------------------------------------------------
 
/** "Active Government Propositions" */
const WP_ACTIVE_PROPS: LangRecord = {
  en: 'Active Government Propositions', sv: 'Aktiva propositioner',
  da: 'Aktive regeringsforslag', no: 'Aktive regjeringsproposisjoner',
  fi: 'Aktiiviset hallituksen esitykset', de: 'Aktive Regierungsvorschlรคge',
  fr: 'Propositions gouvernementales actives', es: 'Proposiciones gubernamentales activas',
  nl: 'Actieve regeringsvoorstellen', ar: 'ู…ู‚ุชุฑุญุงุช ุญูƒูˆู…ูŠุฉ ู†ุดุทุฉ',
  he: 'ื”ืฆืขื•ืช ืžืžืฉืœื” ืคืขื™ืœื•ืช', ja: 'ๆดปๅ‹•ไธญใฎๆ”ฟๅบœๆๆกˆ', ko: 'ํ™œ์„ฑ ์ •๋ถ€ ์ œ์•ˆ', zh: 'ๆดป่ทƒ็š„ๆ”ฟๅบœๆๆกˆ',
};
 
/** "proposition(s) require parliamentary action" */
const WP_PROPS_DESC: Partial<Record<Language, (n: number) => string>> = {
  en: (n) => `${n} proposition${n !== 1 ? 's' : ''} require parliamentary action`,
  sv: (n) => `${n} proposition${n !== 1 ? 'er' : ''} krรคver parlamentarisk behandling`,
  da: (n) => `${n} forslag krรฆver parlamentarisk behandling`,
  no: (n) => `${n} proposisjon${n !== 1 ? 'er' : ''} krever parlamentarisk behandling`,
  fi: (n) => `${n} esitys${n !== 1 ? 'tรค' : ''} vaatii parlamentaarista kรคsittelyรค`,
  de: (n) => `${n} Regierungsvorlage${n !== 1 ? 'n' : ''} erfordern parlamentarische Bearbeitung`,
  fr: (n) => `${n} proposition${n !== 1 ? 's' : ''} nรฉcessitent un examen parlementaire`,
  es: (n) => `${n} proposiciรณn${n !== 1 ? 'es' : ''} requiere${n !== 1 ? 'n' : ''} acciรณn parlamentaria`,
  nl: (n) => `${n} voorstel${n !== 1 ? 'len' : ''} vereisen parlementaire behandeling`,
  ar: (n) => `${n} ู…ู‚ุชุฑุญ${n !== 1 ? 'ุงุช' : ''} ุชุชุทู„ุจ ุฅุฌุฑุงุก ุจุฑู„ู…ุงู†ูŠุง`,
  he: (n) => `${n} ื”ืฆืขื•ืช ื“ื•ืจืฉื•ืช ื˜ื™ืคื•ืœ ืคืจืœืžื ื˜ืจื™`,
  ja: (n) => `${n}ไปถใฎๆๆกˆใŒๅ›ฝไผšๅฏฉ่ญฐใ‚’ๅฟ…่ฆใจใ™ใ‚‹`,
  ko: (n) => `${n}๊ฑด์˜ ์ œ์•ˆ์ด ์˜ํšŒ ์‹ฌ์˜๋ฅผ ํ•„์š”๋กœ ํ•จ`,
  zh: (n) => `${n}้กนๆๆกˆ้œ€่ฆ่ฎฎไผšๅฎก่ฎฎ`,
};
 
/** "Committee Reports to Monitor" */
const WP_COMMITTEE: LangRecord = {
  en: 'Committee Reports to Monitor', sv: 'Utskottsbetรคnkanden att fรถlja',
  da: 'Udvalgsrapporter at fรธlge', no: 'Komitรฉrapporter รฅ fรธlge',
  fi: 'Seurattavat valiokuntamietinnรถt', de: 'Zu beobachtende Ausschussberichte',
  fr: 'Rapports de commission ร  suivre', es: 'Informes de comisiรณn a seguir',
  nl: 'Commissierapporten om te volgen', ar: 'ุชู‚ุงุฑูŠุฑ ุงู„ู„ุฌุงู† ู„ู„ู…ุชุงุจุนุฉ',
  he: 'ื“ื•ื—ื•ืช ื•ืขื“ื•ืช ืœืžืขืงื‘', ja: '็›ฃ่ฆ–ใ™ในใๅง”ๅ“กไผšๅ ฑๅ‘Š', ko: '๋ชจ๋‹ˆํ„ฐ๋งํ•  ์œ„์›ํšŒ ๋ณด๊ณ ์„œ', zh: '้œ€่ฆๅ…ณๆณจ็š„ๅง”ๅ‘˜ไผšๆŠฅๅ‘Š',
};
 
/** "committee report(s) shaping the parliamentary position" */
const WP_COMMITTEE_DESC: Partial<Record<Language, (n: number) => string>> = {
  en: (n) => `${n} committee report${n !== 1 ? 's' : ''} shaping the parliamentary position`,
  sv: (n) => `${n} betรคnkande${n !== 1 ? 'n' : ''} formar den parlamentariska stรฅndpunkten`,
  da: (n) => `${n} udvalgsrapport${n !== 1 ? 'er' : ''} former den parlamentariske holdning`,
  no: (n) => `${n} komitรฉrapport${n !== 1 ? 'er' : ''} former den parlamentariske posisjonen`,
  fi: (n) => `${n} mietintรถ${n !== 1 ? 'รค' : ''} muokkaa parlamentaarista kantaa`,
  de: (n) => `${n} Ausschussbericht${n !== 1 ? 'e' : ''} prรคgen die parlamentarische Position`,
  fr: (n) => `${n} rapport${n !== 1 ? 's' : ''} de commission faรงonnent la position parlementaire`,
  es: (n) => `${n} informe${n !== 1 ? 's' : ''} de comisiรณn moldean la posiciรณn parlamentaria`,
  nl: (n) => `${n} commissierapport${n !== 1 ? 'en' : ''} vormen de parlementaire positie`,
  ar: (n) => `${n} ุชู‚ุฑูŠุฑ${n !== 1 ? 'ุงุช' : ''} ู„ุฌุงู† ุชุดูƒู„ ุงู„ู…ูˆู‚ู ุงู„ุจุฑู„ู…ุงู†ูŠ`,
  he: (n) => `${n} ื“ื•ื—ื•ืช ื•ืขื“ื•ืช ืžืขืฆื‘ื™ื ืืช ืขืžื“ืช ื”ืคืจืœืžื ื˜`,
  ja: (n) => `${n}ไปถใฎๅง”ๅ“กไผšๅ ฑๅ‘ŠใŒ่ญฐไผšใฎ็ซ‹ๅ ดใ‚’ๅฝขๆˆ`,
  ko: (n) => `${n}๊ฑด์˜ ์œ„์›ํšŒ ๋ณด๊ณ ์„œ๊ฐ€ ์˜ํšŒ ์ž…์žฅ์„ ํ˜•์„ฑ`,
  zh: (n) => `${n}ไปฝๅง”ๅ‘˜ไผšๆŠฅๅ‘Šๆญฃๅœจๅก‘้€ ่ฎฎไผš็ซ‹ๅœบ`,
};
 
/** "Enacted Laws in Force" */
const WP_SFS: LangRecord = {
  en: 'Enacted Laws in Force', sv: 'Antagna lagar i kraft',
  da: 'Vedtagne love i kraft', no: 'Vedtatte lover i kraft',
  fi: 'Voimassa olevat lait', de: 'Erlassene Gesetze in Kraft',
  fr: 'Lois promulguรฉes en vigueur', es: 'Leyes promulgadas en vigor',
  nl: 'Uitgevaardigde wetten van kracht', ar: 'ู‚ูˆุงู†ูŠู† ุตุงุฏุฑุฉ ุณุงุฑูŠุฉ ุงู„ู…ูุนูˆู„',
  he: 'ื—ื•ืงื™ื ืฉื ื—ืงืงื• ื‘ืชื•ืงืฃ', ja: 'ๆ–ฝ่กŒไธญใฎๅˆถๅฎšๆณ•', ko: '์‹œํ–‰ ์ค‘์ธ ๋ฒ•๋ฅ ', zh: 'ๅทฒ็”Ÿๆ•ˆ็š„ๆณ•ๅพ‹',
};
 
/** "enacted law(s) establish the legal framework โ€” stakeholders must conduct compliance review" */
const WP_SFS_DESC: Partial<Record<Language, (n: number) => string>> = {
  en: (n) => `${n} enacted law${n !== 1 ? 's' : ''} establish the legal framework โ€” stakeholders must conduct compliance review`,
  sv: (n) => `${n} lag/fรถrordning${n !== 1 ? 'ar' : ''} etablerar rรคttslig ram โ€” intressenter behรถver genomfรถra efterlevnadsgranskning`,
  da: (n) => `${n} lov${n !== 1 ? 'e' : ''} etablerer den juridiske ramme โ€” interessenter skal foretage overholdelsesvurdering`,
  no: (n) => `${n} lov${n !== 1 ? 'er' : ''} etablerer det juridiske rammeverket โ€” interessenter mรฅ gjennomfรธre samsvarsvurdering`,
  fi: (n) => `${n} laki${n !== 1 ? 'a' : ''} muodostaa oikeudellisen kehyksen โ€” sidosryhmien on suoritettava vaatimustenmukaisuustarkistus`,
  de: (n) => `${n} Gesetz${n !== 1 ? 'e' : ''} bilden den Rechtsrahmen โ€” Stakeholder mรผssen Compliance-Prรผfung durchfรผhren`,
  fr: (n) => `${n} loi${n !== 1 ? 's' : ''} รฉtablissent le cadre juridique โ€” les parties prenantes doivent procรฉder ร  un examen de conformitรฉ`,
  es: (n) => `${n} ley${n !== 1 ? 'es' : ''} establecen el marco legal โ€” las partes interesadas deben realizar una revisiรณn de cumplimiento`,
  nl: (n) => `${n} wet${n !== 1 ? 'ten' : ''} vormen het juridische kader โ€” belanghebbenden moeten een nalevingsonderzoek uitvoeren`,
  ar: (n) => `${n} ${n === 1 ? 'ู‚ุงู†ูˆู† ูŠุคุณุณ' : 'ู‚ูˆุงู†ูŠู† ุชุคุณุณ'} ุงู„ุฅุทุงุฑ ุงู„ู‚ุงู†ูˆู†ูŠ โ€” ูŠุฌุจ ุนู„ู‰ ุฃุตุญุงุจ ุงู„ู…ุตู„ุญุฉ ุฅุฌุฑุงุก ู…ุฑุงุฌุนุฉ ุงู„ุงู…ุชุซุงู„`,
  he: (n) => `${n} ื—ื•ืงื™ื ืžื‘ืกืกื™ื ืืช ื”ืžืกื’ืจืช ื”ืžืฉืคื˜ื™ืช โ€” ื‘ืขืœื™ ืขื ื™ื™ืŸ ื—ื™ื™ื‘ื™ื ืœื‘ืฆืข ื‘ื“ื™ืงืช ืฆื™ื•ืช`,
  ja: (n) => `${n}ไปถใฎๅˆถๅฎšๆณ•ใŒๆณ•็š„ๆž ็ต„ใฟใ‚’็ขบ็ซ‹ โ€” ๅˆฉๅฎณ้–ขไฟ‚่€…ใฏใ‚ณใƒณใƒ—ใƒฉใ‚คใ‚ขใƒณใ‚นใƒฌใƒ“ใƒฅใƒผใ‚’ๅฎŸๆ–ฝใ™ในใ`,
  ko: (n) => `${n}๊ฑด์˜ ๋ฒ•๋ฅ ์ด ๋ฒ•์  ํ”„๋ ˆ์ž„์›Œํฌ๋ฅผ ์ˆ˜๋ฆฝ โ€” ์ดํ•ด๊ด€๊ณ„์ž๋Š” ์ปดํ”Œ๋ผ์ด์–ธ์Šค ๊ฒ€ํ† ๋ฅผ ์ˆ˜ํ–‰ํ•ด์•ผ ํ•จ`,
  zh: (n) => `${n}้กนๆณ•ๅพ‹็กฎ็ซ‹ไบ†ๆณ•ๅพ‹ๆก†ๆžถ โ€” ๅˆฉ็›Š็›ธๅ…ณ่€…ๅฟ…้กป่ฟ›่กŒๅˆ่ง„ๅฎกๆŸฅ`,
};
 
/** "Opposition Motions to Track" */
const WP_MOTIONS: LangRecord = {
  en: 'Opposition Motions to Track', sv: 'Oppositionsmotioner att bevaka',
  da: 'Oppositionsforslag at fรธlge', no: 'Opposisjonsmotioner รฅ fรธlge',
  fi: 'Seurattavat oppositioaloitteet', de: 'Oppositionsantrรคge zu verfolgen',
  fr: 'Motions de l\'opposition ร  suivre', es: 'Mociones de la oposiciรณn a seguir',
  nl: 'Oppositiemoties om te volgen', ar: 'ู…ู‚ุชุฑุญุงุช ุงู„ู…ุนุงุฑุถุฉ ู„ู„ู…ุชุงุจุนุฉ',
  he: 'ื”ืฆืขื•ืช ืื•ืคื•ื–ื™ืฆื™ื” ืœืžืขืงื‘', ja: '่ฟฝ่ทกใ™ในใ้‡Žๅ…šๅ‹•่ญฐ', ko: '์ถ”์ ํ•  ์•ผ๋‹น ๋™์˜', zh: '้œ€่ฆ่ทŸ่ธช็š„ๅๅฏนๆดพๅŠจ่ฎฎ',
};
 
/** "motion(s) signal alternative policy directions" */
const WP_MOTIONS_DESC: Partial<Record<Language, (n: number) => string>> = {
  en: (n) => `${n} motion${n !== 1 ? 's' : ''} signal alternative policy directions`,
  sv: (n) => `${n} motion${n !== 1 ? 'er' : ''} signalerar alternativa politiska inriktningar`,
  da: (n) => `${n} forslag signalerer alternative politiske retninger`,
  no: (n) => `${n} motjon${n !== 1 ? 'er' : ''} signaliserer alternative politiske retninger`,
  fi: (n) => `${n} aloite${n !== 1 ? 'tta' : ''} viestii vaihtoehtoisista politiikan suunnista`,
  de: (n) => `${n} ${n !== 1 ? 'Antrรคge signalisieren' : 'Antrag signalisiert'} alternative Politikrichtungen`,
  fr: (n) => `${n} motion${n !== 1 ? 's' : ''} signalent des orientations politiques alternatives`,
  es: (n) => `${n} mociรณn${n !== 1 ? 'es' : ''} seรฑalan direcciones polรญticas alternativas`,
  nl: (n) => `${n} motie${n !== 1 ? 's' : ''} signaleren alternatieve beleidsrichtingen`,
  ar: (n) => `${n} ู…ู‚ุชุฑุญ${n !== 1 ? 'ุงุช' : ''} ุชุดูŠุฑ ุฅู„ู‰ ุงุชุฌุงู‡ุงุช ุณูŠุงุณูŠุฉ ุจุฏูŠู„ุฉ`,
  he: (n) => `${n} ื”ืฆืขื•ืช ืžืกืžื ื•ืช ื›ื™ื•ื•ื ื™ ืžื“ื™ื ื™ื•ืช ื—ืœื•ืคื™ื™ื`,
  ja: (n) => `${n}ไปถใฎๅ‹•่ญฐใŒไปฃๆ›ฟๆ”ฟ็ญ–ใฎๆ–นๅ‘ๆ€งใ‚’็คบๅ”†`,
  ko: (n) => `${n}๊ฑด์˜ ๋™์˜๊ฐ€ ๋Œ€์•ˆ์  ์ •์ฑ… ๋ฐฉํ–ฅ์„ ์‹œ์‚ฌ`,
  zh: (n) => `${n}้กนๅŠจ่ฎฎๆ˜พ็คบๆ›ฟไปฃๆ”ฟ็ญ–ๆ–นๅ‘`,
};
 
/** "EU Dimension" */
const WP_EU: LangRecord = {
  en: 'EU Dimension', sv: 'EU-dimension',
  da: 'EU-dimension', no: 'EU-dimensjon',
  fi: 'EU-ulottuvuus', de: 'EU-Dimension',
  fr: 'Dimension UE', es: 'Dimensiรณn UE',
  nl: 'EU-dimensie', ar: 'ุงู„ุจุนุฏ ุงู„ุฃูˆุฑูˆุจูŠ',
  he: 'ืžืžื“ ืื™ืจื•ืคื™', ja: 'EUๆฌกๅ…ƒ', ko: 'EU ์ฐจ์›', zh: 'EU็ปดๅบฆ',
};
 
/** "EU position paper(s) reveal European dimension โ€” EU law may constrain national policy options" */
const WP_EU_DESC: Partial<Record<Language, (n: number) => string>> = {
  en: (n) => `${n} EU position paper${n !== 1 ? 's' : ''} reveal European dimension โ€” EU law may constrain national policy options`,
  sv: (n) => `${n} EU-faktapromemoria avslรถjar Europaperspektiv โ€” EU-regelverket kan begrรคnsa nationell handlingsfrihet`,
  da: (n) => `${n} EU-positionspapir${n !== 1 ? 'er' : ''} afslรธrer europรฆisk dimension โ€” EU-lovgivning kan begrรฆnse nationale politiske muligheder`,
  no: (n) => `${n} EU-posisjonspapir${n !== 1 ? 'er' : ''} avslรธrer europeisk dimensjon โ€” EU-lovgivning kan begrense nasjonale politiske alternativer`,
  fi: (n) => `${n} EU-asiakirja${n !== 1 ? 'a' : ''} paljastaa eurooppalaisen ulottuvuuden โ€” EU-lainsรครคdรคntรถ voi rajoittaa kansallisia vaihtoehtoja`,
  de: (n) => `${n} EU-Positionspapier${n !== 1 ? 'e' : ''} zeigen die europรคische Dimension โ€” EU-Recht kann nationale Politikoptionen einschrรคnken`,
  fr: (n) => `${n} document${n !== 1 ? 's' : ''} de position UE rรฉvรจlent la dimension europรฉenne โ€” le droit de l'UE peut limiter les options nationales`,
  es: (n) => `${n} documento${n !== 1 ? 's' : ''} de posiciรณn de la UE revelan la dimensiรณn europea โ€” la legislaciรณn de la UE puede limitar las opciones nacionales`,
  nl: (n) => `${n} EU-positiedocument${n !== 1 ? 'en' : ''} onthullen de Europese dimensie โ€” EU-wetgeving kan nationale beleidsopties beperken`,
  ar: (n) => `${n} ${n === 1 ? 'ูˆุซูŠู‚ุฉ ู…ูˆู‚ู ุฃูˆุฑูˆุจูŠ ุชูƒุดู' : 'ูˆุซุงุฆู‚ ู…ูˆู‚ู ุฃูˆุฑูˆุจูŠ ุชูƒุดู'} ุงู„ุจุนุฏ ุงู„ุฃูˆุฑูˆุจูŠ โ€” ู‚ุฏ ูŠู‚ูŠุฏ ู‚ุงู†ูˆู† ุงู„ุงุชุญุงุฏ ุงู„ุฃูˆุฑูˆุจูŠ ุฎูŠุงุฑุงุช ุงู„ุณูŠุงุณุฉ ุงู„ูˆุทู†ูŠุฉ`,
  he: (n) => `${n} ืžืกืžื›ื™ ืขืžื“ื” ืฉืœ ื”ืื™ื—ื•ื“ ื”ืื™ืจื•ืคื™ ื—ื•ืฉืคื™ื ืืช ื”ืžืžื“ ื”ืื™ืจื•ืคื™ โ€” ื—ื•ืง ื”ืื™ื—ื•ื“ ืขืฉื•ื™ ืœื”ื’ื‘ื™ืœ ืืคืฉืจื•ื™ื•ืช ืžื“ื™ื ื™ื•ืช ืœืื•ืžื™ื•ืช`,
  ja: (n) => `${n}ไปถใฎEUๆ„่ฆ‹ๆ›ธใŒๆฌงๅทžๆฌกๅ…ƒใ‚’ๆ˜Ž็คบ โ€” EUๆณ•ใŒๅ›ฝๅ†…ๆ”ฟ็ญ–ใฎ้ธๆŠž่‚ขใ‚’ๅˆถ็ด„ใ™ใ‚‹ๅฏ่ƒฝๆ€ง`,
  ko: (n) => `${n}๊ฑด์˜ EU ์ž…์žฅ ๋ฌธ์„œ๊ฐ€ ์œ ๋Ÿฝ ์ฐจ์›์„ ๋“œ๋Ÿฌ๋ƒ„ โ€” EU๋ฒ•์ด ๊ตญ๋‚ด ์ •์ฑ… ์˜ต์…˜์„ ์ œํ•œํ•  ์ˆ˜ ์žˆ์Œ`,
  zh: (n) => `${n}ไปฝEU็ซ‹ๅœบๆ–‡ไปถๆญ็คบๆฌงๆดฒ็ปดๅบฆ โ€” EUๆณ•ๅพ‹ๅฏ่ƒฝ้™ๅˆถๅ›ฝๅ†…ๆ”ฟ็ญ–้€‰ๆ‹ฉ`,
};
 
/** "Narrative Frames to Monitor" */
const WP_NARRATIVE: LangRecord = {
  en: 'Narrative Frames to Monitor', sv: 'Narrativa ramar att รถvervaka',
  da: 'Narrative rammer at overvรฅge', no: 'Narrative rammer รฅ overvรฅke',
  fi: 'Seurattavat narratiiviset kehykset', de: 'Zu beobachtende narrative Rahmen',
  fr: 'Cadres narratifs ร  surveiller', es: 'Marcos narrativos a supervisar',
  nl: 'Narratieve kaders om te monitoren', ar: 'ุงู„ุฃุทุฑ ุงู„ุณุฑุฏูŠุฉ ู„ู„ู…ุฑุงู‚ุจุฉ',
  he: 'ืžืกื’ืจื•ืช ื ืจื˜ื™ื‘ื™ื•ืช ืœืžืขืงื‘', ja: '็›ฃ่ฆ–ใ™ในใใƒŠใƒฉใƒ†ใ‚ฃใƒ–ใƒ•ใƒฌใƒผใƒ ', ko: '๋ชจ๋‹ˆํ„ฐ๋งํ•  ์„œ์‚ฌ ํ”„๋ ˆ์ž„', zh: '้œ€่ฆ็›‘ๆŽง็š„ๅ™ไบ‹ๆก†ๆžถ',
};
 
/** "Political rhetorical frames identified: " */
const WP_NARRATIVE_DESC: LangRecord = {
  en: 'Political rhetorical frames identified: ', sv: 'Politiska retoriska ramar identifierade: ',
  da: 'Politiske retoriske rammer identificeret: ', no: 'Politiske retoriske rammer identifisert: ',
  fi: 'Poliittisia retorisia kehyksiรค tunnistettu: ', de: 'Politische rhetorische Rahmen identifiziert: ',
  fr: 'Cadres rhรฉtoriques politiques identifiรฉs : ', es: 'Marcos retรณricos polรญticos identificados: ',
  nl: 'Politieke retorische kaders geรฏdentificeerd: ', ar: 'ุชู… ุชุญุฏูŠุฏ ุฃุทุฑ ุจู„ุงุบูŠุฉ ุณูŠุงุณูŠุฉ: ',
  he: 'ืžืกื’ืจื•ืช ืจื˜ื•ืจื™ื•ืช ืคื•ืœื™ื˜ื™ื•ืช ืฉื–ื•ื”ื•: ', ja: 'ๆ”ฟๆฒป็š„ไฟฎ่พžใƒ•ใƒฌใƒผใƒ ็‰นๅฎš: ', ko: '์ •์น˜์  ์ˆ˜์‚ฌ ํ”„๋ ˆ์ž„ ํ™•์ธ: ', zh: 'ๅทฒ่ฏ†ๅˆซ็š„ๆ”ฟๆฒปไฟฎ่พžๆก†ๆžถ: ',
};
 
// ---------------------------------------------------------------------------
// Dashboard labels (14 languages)
// ---------------------------------------------------------------------------
 
const DASHBOARD_TITLE: LangRecord = {
  en: 'Document Intelligence', sv: 'Dokumentintelligens',
  da: 'Dokumentefterretning', no: 'Dokumentetterretning',
  fi: 'Asiakirjatiedustelu', de: 'Dokumentenintelligenz',
  fr: 'Renseignement documentaire', es: 'Inteligencia documental',
  nl: 'Documentintelligentie', ar: 'ุงุณุชุฎุจุงุฑุงุช ุงู„ูˆุซุงุฆู‚',
  he: 'ืžื•ื“ื™ืขื™ืŸ ืžืกืžื›ื™ื', ja: 'ๆ–‡ๆ›ธใ‚คใƒณใƒ†ใƒชใ‚ธใ‚งใƒณใ‚น', ko: '๋ฌธ์„œ ์ธํ…”๋ฆฌ์ „์Šค', zh: 'ๆ–‡ไปถๆƒ…ๆŠฅ',
};
 
const DASHBOARD_DOCS_ANALYSED: Partial<Record<Language, (n: number) => string>> = {
  en: (n) => `${n} parliamentary document${n !== 1 ? 's' : ''} analysed`,
  sv: (n) => `${n} riksdagsdokument ${n !== 1 ? 'analyserade' : 'analyserat'}`,
  da: (n) => `${n} parlamentsdokument${n !== 1 ? 'er' : ''} analyseret`,
  no: (n) => `${n} parlamentsdokument${n !== 1 ? 'er' : ''} analysert`,
  fi: (n) => `${n} asiakirja${n !== 1 ? 'a' : ''} analysoitu`,
  de: (n) => `${n} parlamentarische${n === 1 ? 's' : ''} Dokument${n !== 1 ? 'e' : ''} analysiert`,
  fr: (n) => `${n} document${n !== 1 ? 's' : ''} parlementaire${n !== 1 ? 's' : ''} analysรฉ${n !== 1 ? 's' : ''}`,
  es: (n) => `${n} documento${n !== 1 ? 's' : ''} parlamentario${n !== 1 ? 's' : ''} analizado${n !== 1 ? 's' : ''}`,
  nl: (n) => `${n} parlementair${n !== 1 ? 'e' : ''} document${n !== 1 ? 'en' : ''} geanalyseerd`,
  ar: (n) => `${n} ูˆุซูŠู‚ุฉ ุจุฑู„ู…ุงู†ูŠุฉ ุชู… ุชุญู„ูŠู„ู‡ุง`,
  he: (n) => `${n} ืžืกืžื›ื™ื ืคืจืœืžื ื˜ืจื™ื™ื ื ื•ืชื—ื•`,
  ja: (n) => `${n}ไปถใฎ่ญฐไผšๆ–‡ๆ›ธใ‚’ๅˆ†ๆž`,
  ko: (n) => `${n}๊ฑด์˜ ์˜ํšŒ ๋ฌธ์„œ ๋ถ„์„๋จ`,
  zh: (n) => `${n}ไปฝ่ฎฎไผšๆ–‡ไปถๅทฒๅˆ†ๆž`,
};
 
// ---------------------------------------------------------------------------
// Policy narrative labels (14 languages)
// ---------------------------------------------------------------------------
 
const NARRATIVE_ANALYSIS_OF: LangRecord = {
  en: 'Analysis of', sv: 'Analys av',
  da: 'Analyse af', no: 'Analyse av',
  fi: 'Analyysi', de: 'Analyse von',
  fr: 'Analyse de', es: 'Anรกlisis de',
  nl: 'Analyse van', ar: 'ุชุญู„ูŠู„',
  he: 'ื ื™ืชื•ื—', ja: 'ๅˆ†ๆž:', ko: '๋ถ„์„:', zh: 'ๅˆ†ๆž',
};
 
const NARRATIVE_REVEALS: LangRecord = {
  en: 'reveals', sv: 'visar',
  da: 'afslรธrer', no: 'avslรธrer',
  fi: 'paljastaa', de: 'zeigt',
  fr: 'rรฉvรจle', es: 'revela',
  nl: 'onthult', ar: 'ูŠูƒุดู',
  he: 'ื—ื•ืฉืฃ', ja: 'ใŒ็คบใ™', ko: '์ด(๊ฐ€) ๋“œ๋Ÿฌ๋‚จ', zh: 'ๆญ็คบ',
};
 
const NARRATIVE_POLICY_ACTIVITY: LangRecord = {
  en: 'policy activity in', sv: 'politikaktivitet inom',
  da: 'politisk aktivitet i', no: 'politisk aktivitet innen',
  fi: 'poliittista toimintaa alueella', de: 'politische Aktivitรคt in',
  fr: 'activitรฉ politique dans', es: 'actividad polรญtica en',
  nl: 'beleidsactiviteit in', ar: 'ู†ุดุงุท ุณูŠุงุณูŠ ููŠ',
  he: 'ืคืขื™ืœื•ืช ืžื“ื™ื ื™ื•ืชื™ืช ื‘', ja: 'ใฎๆ”ฟ็ญ–ๆดปๅ‹•', ko: '์˜ ์ •์ฑ… ํ™œ๋™', zh: 'ไธญ็š„ๆ”ฟ็ญ–ๆดปๅŠจ',
};
 
const NARRATIVE_PARLIAMENTARY_ACTIVITY: LangRecord = {
  en: 'parliamentary activity', sv: 'parlamentarisk aktivitet',
  da: 'parlamentarisk aktivitet', no: 'parlamentarisk aktivitet',
  fi: 'parlamentaarista toimintaa', de: 'parlamentarische Aktivitรคt',
  fr: 'activitรฉ parlementaire', es: 'actividad parlamentaria',
  nl: 'parlementaire activiteit', ar: 'ู†ุดุงุท ุจุฑู„ู…ุงู†ูŠ',
  he: 'ืคืขื™ืœื•ืช ืคืจืœืžื ื˜ืจื™ืช', ja: '่ญฐไผšๆดปๅ‹•', ko: '์˜ํšŒ ํ™œ๋™', zh: '่ฎฎไผšๆดปๅŠจ',
};
 
const NARRATIVE_WITH_FULL_TEXT: Partial<Record<Language, (total: number, enriched: number) => string>> = {
  en: (t, e) => `${t} documents (${e} with enriched full text)`,
  sv: (t, e) => `${t} dokument (${e} med berikad fulltext)`,
  da: (t, e) => `${t} dokumenter (${e} med beriget fuldtekst)`,
  no: (t, e) => `${t} dokumenter (${e} med beriket fulltekst)`,
  fi: (t, e) => `${t} asiakirjaa (${e} rikastetulla kokotekstillรค)`,
  de: (t, e) => `${t} Dokumente (${e} mit angereichertem Volltext)`,
  fr: (t, e) => `${t} documents (${e} avec texte intรฉgral enrichi)`,
  es: (t, e) => `${t} documentos (${e} con texto completo enriquecido)`,
  nl: (t, e) => `${t} documenten (${e} met verrijkte volledige tekst)`,
  ar: (t, e) => `${t} ูˆุซูŠู‚ุฉ (${e} ุจู†ุต ูƒุงู…ู„ ู…ูุซุฑู‰)`,
  he: (t, e) => `${t} ืžืกืžื›ื™ื (${e} ืขื ื˜ืงืกื˜ ืžืœื ืžื•ืขืฉืจ)`,
  ja: (t, e) => `${t}ไปถใฎๆ–‡ๆ›ธ (${e}ไปถใฏใƒ•ใƒซใƒ†ใ‚ญใ‚นใƒˆๅ……ๅฎŸ)`,
  ko: (t, e) => `${t}๊ฑด์˜ ๋ฌธ์„œ (${e}๊ฑด ์ „๋ฌธ ๋ณด๊ฐ•)`,
  zh: (t, e) => `${t}ไปฝๆ–‡ไปถ (${e}ไปฝๅซๅฎŒๆ•ดๆ–‡ๆœฌ)`,
};
 
const NARRATIVE_WITH_METADATA: Partial<Record<Language, (total: number, enriched: number) => string>> = {
  en: (t, e) => `${t} documents (${e} with enriched metadata)`,
  sv: (t, e) => `${t} dokument (${e} med berikad metadata)`,
  da: (t, e) => `${t} dokumenter (${e} med beriget metadata)`,
  no: (t, e) => `${t} dokumenter (${e} med beriket metadata)`,
  fi: (t, e) => `${t} asiakirjaa (${e} rikastetulla metatiedolla)`,
  de: (t, e) => `${t} Dokumente (${e} mit angereicherten Metadaten)`,
  fr: (t, e) => `${t} documents (${e} avec mรฉtadonnรฉes enrichies)`,
  es: (t, e) => `${t} documentos (${e} con metadatos enriquecidos)`,
  nl: (t, e) => `${t} documenten (${e} met verrijkte metadata)`,
  ar: (t, e) => `${t} ูˆุซูŠู‚ุฉ (${e} ุจุจูŠุงู†ุงุช ูˆุตููŠุฉ ู…ูุซุฑูŠุฉ)`,
  he: (t, e) => `${t} ืžืกืžื›ื™ื (${e} ืขื ืžื˜ื-ื ืชื•ื ื™ื ืžื•ืขืฉืจื™ื)`,
  ja: (t, e) => `${t}ไปถใฎๆ–‡ๆ›ธ (${e}ไปถใฏใƒกใ‚ฟใƒ‡ใƒผใ‚ฟๅ……ๅฎŸ)`,
  ko: (t, e) => `${t}๊ฑด์˜ ๋ฌธ์„œ (${e}๊ฑด ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ๋ณด๊ฐ•)`,
  zh: (t, e) => `${t}ไปฝๆ–‡ไปถ (${e}ไปฝๅซไธฐๅฏŒๅ…ƒๆ•ฐๆฎ)`,
};
 
const NARRATIVE_FOCUS: LangRecord = {
  en: 'with focus on', sv: 'med fokus pรฅ',
  da: 'med fokus pรฅ', no: 'med fokus pรฅ',
  fi: 'painopisteenรค', de: 'mit Fokus auf',
  fr: 'avec un accent sur', es: 'con enfoque en',
  nl: 'met focus op', ar: 'ู…ุน ุงู„ุชุฑูƒูŠุฒ ุนู„ู‰',
  he: 'ืขื ื“ื’ืฉ ืขืœ', ja: 'ใซ็„ฆ็‚นใ‚’ๅฝ“ใฆใฆ', ko: '์— ์ดˆ์ ์„ ๋งž์ถ”์–ด', zh: '้‡็‚นๅ…ณๆณจ',
};
 
function docType(doc: RawDocument): string {
  return (doc.doktyp || doc.documentType || '').toLowerCase();
}
 
function docTitle(doc: RawDocument): string {
  return (doc.titel || doc.title || doc.dokumentnamn || doc.dok_id || '').trim();
}
 
function docId(doc: RawDocument): string {
  return doc.dok_id || doc.url || doc.titel || doc.title || doc.dokumentnamn || 'unknown';
}
 
/** Test whether a document is an SFS (enacted law/statute) โ€” matches both `doktyp === 'sfs'` and `dokumentnamn` starting with 'SFS'. */
function isSfsDoc(doc: RawDocument): boolean {
  return docType(doc) === 'sfs' || (doc.dokumentnamn || '').startsWith('SFS');
}
 
/**
 * Normalize document type key, treating SFS-by-name documents (missing `doktyp`
 * but with `dokumentnamn` starting with 'SFS') as `'sfs'` and empty types as `'other'`.
 * Reuse this everywhere a doc-type key is needed (mindmap, dashboard, confidence).
 */
function normalizedDocType(doc: RawDocument): string {
  const raw = docType(doc);
  if (raw === 'eu') return 'fpm';    // EU position papers ('eu') are foreign policy matters ('fpm') โ€” normalize for consistent dashboard/localization labels
  if (raw) return raw;
  if (isSfsDoc(doc)) return 'sfs';
  return 'other';
}
 
/**
 * Predicate: document metadata was enriched via `enrichDocumentsWithContent()`.
 *
 * `contentFetched` is set when the MCP client retrieves document details
 * (title, summary, organ, notis, etc.) โ€” even when called with
 * `include_full_text=false`. This is the normal case for Riksdag documents.
 *
 * Use for: enrichedCount, confidence scoring baseline, validation messaging.
 */
function isMetadataEnriched(doc: RawDocument): boolean {
  return Boolean(doc.contentFetched);
}
 
/**
 * Predicate: document has full-text or full-HTML content available.
 *
 * This is a stricter check than `isMetadataEnriched`: it requires the
 * document to actually have downloadable text/HTML body, which only happens
 * when the MCP client is called with `include_full_text=true` (or when the
 * field is populated by other means).
 *
 * Use for: passage extraction, deep text analysis, HIGH-confidence SWOT.
 */
function hasFullTextContent(doc: RawDocument): boolean {
  return Boolean(doc.contentFetched && (doc.fullText || doc.fullContent));
}
 
/** Extract a meaningful text passage from an enriched document. */
function extractPassage(doc: RawDocument, maxChars = 400): string | null {
  const raw = doc.fullText || doc.fullContent || '';
  if (!raw || isPersonProfileText(raw)) return null;
  const cleaned = docType(doc) === 'mot' && raw.includes('Motion till riksdagen')
    ? cleanMotionText(raw)
    : raw;
  return extractKeyPassage(cleaned, maxChars) || null;
}
 
/**
 * Return a SwotEntry text built from a document title โ€” concise but explicit.
 * Returns plain text; HTML-escaping happens at the render site (section generators).
 */
function entryFromDoc(doc: RawDocument, topic: string | null, lang: Language): string {
  const title = docTitle(doc);
  const type = normalizedDocType(doc);
  const typeLabel = type && type !== 'other' ? localizeDocType(type, lang, 1) : '';
 
  if (topic) {
    // Explicit relevance framing when a focus topic is present
    const relevance = relevantLabel(lang);
    return typeLabel
      ? `${typeLabel}: ${title} โ€” ${relevance} ${topic}`
      : `${title} โ€” ${relevance} ${topic}`;
  }
  return typeLabel ? `${typeLabel}: ${title}` : title;
}
 
/** Small localised phrase: "relevant to" / "relevant fรถr" โ€ฆ */
function relevantLabel(lang: Language): string {
  const map: LangRecord = {
    en: 'relevant to', sv: 'relevant fรถr', da: 'relevant for', no: 'relevant for',
    fi: 'liittyy', de: 'relevant fรผr', fr: 'pertinent pour', es: 'relevante para',
    nl: 'relevant voor', ar: 'ุฐูˆ ุตู„ุฉ ุจู€', he: 'ืจืœื•ื•ื ื˜ื™ ืœ', ja: 'ใซ้–ข้€ฃ:', ko: '๊ด€๋ จ:', zh: '็›ธๅ…ณ:',
  };
  return map[lang] ?? 'relevant to';
}
 
/** Derive impact from document type: propositions/laws/committee reports/EU positions are high, motions/government comms/press medium, rest low. */
function impactFromDocType(dt: string): 'high' | 'medium' | 'low' {
  if (['prop', 'sfs', 'bet', 'fpm', 'eu'].includes(dt)) return 'high';
  if (['mot', 'skr', 'pressm'].includes(dt)) return 'medium';
  return 'low';
}
 
/** Build a content-derived SWOT entry from full-text passage when available. */
function buildEnrichedEntry(
  doc: RawDocument,
  topic: string | null,
  lang: Language,
  passageMaxChars: number,
): AnalysisSwotEntry {
  const passage = extractPassage(doc, passageMaxChars);
  const type = normalizedDocType(doc);
  const domainAnalysis = detectPolicyDomains(doc, lang);
  const domainText = domainAnalysis.length > 0
    ? getDomainSpecificAnalysis(domainAnalysis[0]!, type, lang)
    : '';
 
  let text: string;
  if (passage) {
    // Content-derived: lead with passage excerpt, append domain context
    text = domainText ? `${passage} โ€” ${domainText}` : passage;
  } else {
    // Metadata-derived: title + domain context
    text = entryFromDoc(doc, topic, lang);
    if (domainText) text = `${text}. ${domainText}`;
  }
 
  return {
    text,
    impact: impactFromDocType(type),
    sourceDocIds: [docId(doc)].filter(Boolean),
    confidence: passage ? 'HIGH' : isMetadataEnriched(doc) ? 'MEDIUM' : 'LOW',
  };
}
 
/** Build a structural placeholder entry when no documents exist for a quadrant. */
function placeholderEntry(
  role: string,
  quadrant: string,
  topic: string | null,
  lang: Language,
  domains: string[],
): AnalysisSwotEntry {
  const primaryDomain = domains[0] ?? null;
  const text = buildPlaceholderText(role, quadrant, topic, primaryDomain, lang);
  return {
    text,
    impact: quadrant === 'strengths' || quadrant === 'opportunities' ? 'medium' : 'low',
    sourceDocIds: [],
    confidence: 'LOW',
  };
}
 
// ---------------------------------------------------------------------------
// Placeholder text builders โ€” structural fallbacks for when no document evidence
// is available for a SWOT quadrant. These are NOT the primary analysis text;
// they are only used when a stakeholder ร— quadrant combination has no matching
// documents. In document-rich analyses, every SWOT entry is content-derived.
// Future LLM integration point: replace this function with an API call.
// ---------------------------------------------------------------------------
 
/**
 * Build a structural fallback SWOT text from role ร— quadrant ร— topic ร— domain.
 * Used only when no document evidence exists for a particular quadrant;
 * content-derived entries always take precedence over these placeholders.
 * Each placeholder is contextualised with the focus topic and primary domain
 * to keep entries relevant even without direct document backing.
 */
function buildPlaceholderText(
  role: string,
  quadrant: string,
  topic: string | null,
  domain: string | null,
  lang: Language,
): string {
  const topicFrag = topic ? ` (${topic})` : '';
  const domainFrag = domain ? ` in ${domain}` : '';
 
  // English composition โ€” other languages use the same structure for consistency
  // Future AI integration point: replace this function with an LLM prompt.
  const compositions: Record<string, Record<string, string>> = {
    government: {
      strengths: `Legislative authority and executive agenda-setting capacity${topicFrag}${domainFrag} through government propositions and statutory instruments`,
      weaknesses: `Implementation timeline risks and resource allocation challenges${topicFrag}${domainFrag} requiring interagency coordination`,
      opportunities: `EU regulatory alignment and international cooperation frameworks${topicFrag}${domainFrag} for policy advancement`,
      threats: `Parliamentary opposition scrutiny and committee amendment risks${topicFrag}${domainFrag} that may delay or modify legislative outcomes`,
    },
    parliament: {
      strengths: `Oversight mandate and cross-committee scrutiny capacity${topicFrag}${domainFrag} through committee reports and chamber debates`,
      weaknesses: `Information asymmetry relative to executive branch${topicFrag}${domainFrag} on implementation details and classified material`,
      opportunities: `Cross-party consensus-building and coalition amendment capacity${topicFrag}${domainFrag} to strengthen legislation`,
      threats: `Government majority limiting effective amendment capacity${topicFrag}${domainFrag} in committee and chamber votes`,
    },
    'private-sector': {
      strengths: `Domain expertise, operational capacity, and sector-specific knowledge${topicFrag}${domainFrag} influencing policy design`,
      weaknesses: `Compliance adaptation burden and regulatory uncertainty${topicFrag}${domainFrag} creating planning challenges`,
      opportunities: `Policy-driven investment, innovation potential, and market development${topicFrag}${domainFrag}`,
      threats: `Rapid policy evolution and short implementation timelines${topicFrag}${domainFrag} creating competitive uncertainty`,
    },
  };
 
  const roleCompositions = compositions[role] ?? compositions['government']!;
  const text = roleCompositions[quadrant] ?? `Policy analysis${topicFrag}${domainFrag}`;
 
  // Apply language-specific framing for non-English outputs
  return applyLanguageFraming(text, lang, role, quadrant, topic, domain);
}
 
// ---------------------------------------------------------------------------
// SWOT composition builders (module-level constant โ€” hoisted from applyLanguageFraming)
// ---------------------------------------------------------------------------
 
type SwotRoleCompositions = Record<string, Record<string, string>>;
type SwotCompositionBuilder = (topicFrag: string, domainFrag: string) => SwotRoleCompositions;
 
/**
 * Per-language SWOT placeholder composition builders.
 * Covers sv, da, no, fi, de, fr, es, nl, ar, he, ja, ko, zh (13 non-English languages).
 * English is handled by the caller (applyLanguageFraming returns enText directly).
 * Languages not present fall back to English via the caller's default path.
 */
const SWOT_LANGUAGE_BUILDERS: Partial<Record<Language, { domainPrep: string; builder: SwotCompositionBuilder }>> = {
  sv: {
    domainPrep: 'inom',
    builder: (tf, df) => ({
      government: {
        strengths: `Lagstiftningsbehรถrighet och exekutiv agendasรคttningskapacitet${tf}${df} genom propositioner och fรถrordningar`,
        weaknesses: `Genomfรถranderisker och resursallokeringsutmaningar${tf}${df} som krรคver myndighetssamordning`,
        opportunities: `EU-reglering och internationella samarbetsramverk${tf}${df} fรถr politikutveckling`,
        threats: `Parlamentarisk oppositionsgranskning och utskottsรคndringsrisker${tf}${df} som kan fรถrdrรถja eller modifiera lagstiftningsresultat`,
      },
      parliament: {
        strengths: `Tillsynsmandat och utskottsgranskning${tf}${df} genom betรคnkanden och kammardebatten`,
        weaknesses: `Informationsasymmetri gentemot den exekutiva grenen${tf}${df} i genomfรถrandedetaljer`,
        opportunities: `Konsensusbyggande รถver partigrรคnser${tf}${df} fรถr att stรคrka lagstiftning`,
        threats: `Regeringsmajoriteten begrรคnsar effektiv รคndringskapacitet${tf}${df} i utskott och kammare`,
      },
      'private-sector': {
        strengths: `Domรคnexpertis, operativ kapacitet och sektorsspecifik kunskap${tf}${df} som pรฅverkar policyutformning`,
        weaknesses: `Efterlevnadsanpassningsbรถrda och regulatorisk osรคkerhet${tf}${df} som skapar planeringsutmaningar`,
        opportunities: `Policydriven investering, innovationspotential och marknadsutveckling${tf}${df}`,
        threats: `Snabb policyutveckling och korta genomfรถrandetidsplaner${tf}${df} skapar konkurrensmรคssig osรคkerhet`,
      },
    }),
  },
    da: {
      domainPrep: 'inden for',
      builder: (tf, df) => ({
        government: {
          strengths: `Lovgivningsmyndighed og dagsordensรฆttende kapacitet${tf}${df} gennem regeringsforslag og lovgivningsinstrumenter`,
          weaknesses: `Implementeringsrisici og ressourceallokeringsudfordringer${tf}${df} der krรฆver tvรฆrministeriel koordinering`,
          opportunities: `EU-reguleringstilpasning og internationale samarbejdsrammer${tf}${df} for politikudvikling`,
          threats: `Parlamentarisk oppositionsgranskning og udvalgsรฆndringsrisici${tf}${df} der kan forsinke eller รฆndre lovgivningsresultater`,
        },
        parliament: {
          strengths: `Tilsynsmandat og tvรฆrudvalgs-granskning${tf}${df} gennem betรฆnkninger og kammerdebatter`,
          weaknesses: `Informationsasymmetri i forhold til den udรธvende magt${tf}${df} om implementeringsdetaljer`,
          opportunities: `Konsensusopbygning pรฅ tvรฆrs af partier${tf}${df} for at styrke lovgivningen`,
          threats: `Regeringsflertal begrรฆnser effektiv รฆndringskapacitet${tf}${df} i udvalg og kamre`,
        },
        'private-sector': {
          strengths: `Domรฆneekspertise, operationel kapacitet og sektorspecifik viden${tf}${df} der pรฅvirker politikudformning`,
          weaknesses: `Compliance-tilpasningsbyrde og regulatorisk usikkerhed${tf}${df} der skaber planlรฆgningsudfordringer`,
          opportunities: `Politikdrevet investering, innovationspotentiale og markedsudvikling${tf}${df}`,
          threats: `Hurtig politikudvikling og korte implementeringstidslinjer${tf}${df} der skaber konkurrencemรฆssig usikkerhed`,
        },
      }),
    },
    no: {
      domainPrep: 'innen',
      builder: (tf, df) => ({
        government: {
          strengths: `Lovgivningsmyndighet og dagsordensettende kapasitet${tf}${df} gjennom regjeringsforslag og lovgivningsinstrumenter`,
          weaknesses: `Implementeringsrisikoer og ressursallokeringsutfordringer${tf}${df} som krever tverretatlig koordinering`,
          opportunities: `EU-reguleringstilpasning og internasjonale samarbeidsrammer${tf}${df} for politikkutvikling`,
          threats: `Parlamentarisk opposisjonsgranskning og komitรฉendringsrisikoer${tf}${df} som kan forsinke eller endre lovgivningsresultater`,
        },
        parliament: {
          strengths: `Tilsynsmandat og tverrkomitรฉgranskning${tf}${df} gjennom komitรฉinnstillinger og kammerdebatter`,
          weaknesses: `Informasjonsasymmetri overfor den utรธvende makt${tf}${df} om implementeringsdetaljer`,
          opportunities: `Konsensusbygging pรฅ tvers av partier${tf}${df} for รฅ styrke lovgivningen`,
          threats: `Regjeringsflertall begrenser effektiv endringskapasitet${tf}${df} i komiteer og kamre`,
        },
        'private-sector': {
          strengths: `Domeneekspertise, operasjonell kapasitet og sektorspesifikk kunnskap${tf}${df} som pรฅvirker politikkutforming`,
          weaknesses: `Etterlevelsestilpasningsbyrde og regulatorisk usikkerhet${tf}${df} som skaper planleggingsutfordringer`,
          opportunities: `Politikkdrevet investering, innovasjonspotensial og markedsutvikling${tf}${df}`,
          threats: `Rask politikkutvikling og korte implementeringstidslinjer${tf}${df} som skaper konkurransemessig usikkerhet`,
        },
      }),
    },
    fi: {
      domainPrep: 'alueella',
      builder: (tf, df) => ({
        government: {
          strengths: `Lainsรครคdรคntรถvalta ja toimeenpanovallan agendanasettamiskyky${tf}${df} hallituksen esitysten ja asetusten kautta`,
          weaknesses: `Tรคytรคntรถรถnpanoriskit ja resurssien kohdentamishaasteet${tf}${df} edellyttรคvรคt hallinnonalojen vรคlistรค koordinointia`,
          opportunities: `EU-sรครคntelyn yhdenmukaistaminen ja kansainvรคliset yhteistyรถkehykset${tf}${df} politiikan edistรคmiseksi`,
          threats: `Eduskuntaopposition valvonta ja valiokunnan muutosriskit${tf}${df} voivat viivรคstyttรครค tai muuttaa lainsรครคdรคntรถtuloksia`,
        },
        parliament: {
          strengths: `Valvontamandaatti ja valiokuntien vรคlinen tarkastelu${tf}${df} mietintรถjen ja tรคysistuntokeskustelujen kautta`,
          weaknesses: `Tietoepรคsymmetria toimeenpanovallan suhteen${tf}${df} tรคytรคntรถรถnpanon yksityiskohdissa`,
          opportunities: `Puoluerajat ylittรคvรค konsensuksen rakentaminen${tf}${df} lainsรครคdรคnnรถn vahvistamiseksi`,
          threats: `Hallituksen enemmistรถ rajoittaa tehokasta muutoskykyรค${tf}${df} valiokunnissa ja tรคysistunnoissa`,
        },
        'private-sector': {
          strengths: `Alan asiantuntemus, operatiivinen kapasiteetti ja sektorikohtainen tieto${tf}${df} vaikuttavat politiikan suunnitteluun`,
          weaknesses: `Sรครคdรถsten noudattamisen sopeutumisrasite ja sรครคntely-epรคvarmuus${tf}${df} luovat suunnitteluhaasteita`,
          opportunities: `Politiikkalรคhtรถinen investointi, innovaatiopotentiaali ja markkinakehitys${tf}${df}`,
          threats: `Nopea politiikkakehitys ja lyhyet tรคytรคntรถรถnpanoaikataulut${tf}${df} luovat kilpailullista epรคvarmuutta`,
        },
      }),
    },
    de: {
      domainPrep: 'im Bereich',
      builder: (tf, df) => ({
        government: {
          strengths: `Gesetzgebungskompetenz und exekutive Agenda-Setting-Kapazitรคt${tf}${df} durch Regierungsvorlagen und Verordnungen`,
          weaknesses: `Umsetzungsrisiken und Ressourcenallokationsherausforderungen${tf}${df} die behรถrdenรผbergreifende Koordinierung erfordern`,
          opportunities: `EU-Regulierungsanpassung und internationale Kooperationsrahmen${tf}${df} fรผr Politikentwicklung`,
          threats: `Parlamentarische Oppositionsprรผfung und Ausschussรคnderungsrisiken${tf}${df} die Gesetzgebungsergebnisse verzรถgern oder รคndern kรถnnen`,
        },
        parliament: {
          strengths: `Aufsichtsmandat und ausschussรผbergreifende Prรผfung${tf}${df} durch Berichte und Kammerdebatten`,
          weaknesses: `Informationsasymmetrie gegenรผber der Exekutive${tf}${df} bei Umsetzungsdetails`,
          opportunities: `Parteiรผbergreifender Konsensaufbau${tf}${df} zur Stรคrkung der Gesetzgebung`,
          threats: `Regierungsmehrheit beschrรคnkt effektive ร„nderungskapazitรคt${tf}${df} in Ausschรผssen und Kammern`,
        },
        'private-sector': {
          strengths: `Fachkompetenz, operative Kapazitรคt und branchenspezifisches Wissen${tf}${df} mit Einfluss auf Politikgestaltung`,
          weaknesses: `Compliance-Anpassungslast und regulatorische Unsicherheit${tf}${df} die Planungsherausforderungen schaffen`,
          opportunities: `Politikgetriebene Investitionen, Innovationspotenzial und Marktentwicklung${tf}${df}`,
          threats: `Schnelle Politikentwicklung und kurze Umsetzungsfristen${tf}${df} schaffen wettbewerbliche Unsicherheit`,
        },
      }),
    },
    fr: {
      domainPrep: 'dans le domaine',
      builder: (tf, df) => ({
        government: {
          strengths: `Autoritรฉ lรฉgislative et capacitรฉ d'รฉtablissement de l'agenda exรฉcutif${tf}${df} ร  travers propositions et instruments rรฉglementaires`,
          weaknesses: `Risques de mise en ล“uvre et dรฉfis d'allocation des ressources${tf}${df} nรฉcessitant une coordination interministรฉrielle`,
          opportunities: `Alignement rรฉglementaire UE et cadres de coopรฉration internationale${tf}${df} pour le dรฉveloppement politique`,
          threats: `Contrรดle de l'opposition parlementaire et risques d'amendement en commission${tf}${df} pouvant retarder ou modifier les rรฉsultats lรฉgislatifs`,
        },
        parliament: {
          strengths: `Mandat de surveillance et examen transversal en commission${tf}${df} ร  travers rapports et dรฉbats en sรฉance`,
          weaknesses: `Asymรฉtrie d'information face au pouvoir exรฉcutif${tf}${df} sur les dรฉtails de mise en ล“uvre`,
          opportunities: `Construction de consensus transpartisan${tf}${df} pour renforcer la lรฉgislation`,
          threats: `La majoritรฉ gouvernementale limite la capacitรฉ effective d'amendement${tf}${df} en commission et en sรฉance`,
        },
        'private-sector': {
          strengths: `Expertise sectorielle, capacitรฉ opรฉrationnelle et connaissances spรฉcifiques${tf}${df} influenรงant l'รฉlaboration des politiques`,
          weaknesses: `Charge d'adaptation ร  la conformitรฉ et incertitude rรฉglementaire${tf}${df} crรฉant des dรฉfis de planification`,
          opportunities: `Investissement guidรฉ par les politiques, potentiel d'innovation et dรฉveloppement de marchรฉ${tf}${df}`,
          threats: `ร‰volution rapide des politiques et dรฉlais de mise en ล“uvre courts${tf}${df} crรฉant une incertitude concurrentielle`,
        },
      }),
    },
    es: {
      domainPrep: 'en el รกmbito de',
      builder: (tf, df) => ({
        government: {
          strengths: `Autoridad legislativa y capacidad ejecutiva de establecimiento de agenda${tf}${df} mediante proposiciones y instrumentos normativos`,
          weaknesses: `Riesgos de implementaciรณn y desafรญos de asignaciรณn de recursos${tf}${df} que requieren coordinaciรณn interinstitucional`,
          opportunities: `Alineaciรณn regulatoria de la UE y marcos de cooperaciรณn internacional${tf}${df} para el avance polรญtico`,
          threats: `Escrutinio de la oposiciรณn parlamentaria y riesgos de enmienda en comisiรณn${tf}${df} que pueden retrasar o modificar resultados legislativos`,
        },
        parliament: {
          strengths: `Mandato de supervisiรณn y escrutinio transversal en comisiรณn${tf}${df} mediante informes y debates en pleno`,
          weaknesses: `Asimetrรญa de informaciรณn frente al poder ejecutivo${tf}${df} en detalles de implementaciรณn`,
          opportunities: `Construcciรณn de consenso entre partidos${tf}${df} para fortalecer la legislaciรณn`,
          threats: `La mayorรญa gubernamental limita la capacidad efectiva de enmienda${tf}${df} en comisiรณn y pleno`,
        },
        'private-sector': {
          strengths: `Experiencia sectorial, capacidad operativa y conocimiento especรญfico${tf}${df} que influye en el diseรฑo de polรญticas`,
          weaknesses: `Carga de adaptaciรณn al cumplimiento e incertidumbre regulatoria${tf}${df} que genera desafรญos de planificaciรณn`,
          opportunities: `Inversiรณn impulsada por polรญticas, potencial de innovaciรณn y desarrollo de mercado${tf}${df}`,
          threats: `Evoluciรณn rรกpida de polรญticas y plazos de implementaciรณn cortos${tf}${df} que generan incertidumbre competitiva`,
        },
      }),
    },
    nl: {
      domainPrep: 'op het gebied van',
      builder: (tf, df) => ({
        government: {
          strengths: `Wetgevende bevoegdheid en uitvoerende agendabepalende capaciteit${tf}${df} via wetsvoorstellen en regelgevende instrumenten`,
          weaknesses: `Implementatierisico's en uitdagingen bij toewijzing van middelen${tf}${df} die interdepartementale coรถrdinatie vereisen`,
          opportunities: `EU-regelgevingsafstemming en internationale samenwerkingskaders${tf}${df} voor beleidsontwikkeling`,
          threats: `Parlementaire oppositiecontrole en commissieamenderingsrisico's${tf}${df} die wetgevingsresultaten kunnen vertragen of wijzigen`,
        },
        parliament: {
          strengths: `Toezichtsmandaat en commissie-overstijgend onderzoek${tf}${df} via rapporten en Kamerdebatten`,
          weaknesses: `Informatieasymmetrie ten opzichte van de uitvoerende macht${tf}${df} over implementatiedetails`,
          opportunities: `Partijoverstijgende consensusvorming${tf}${df} om wetgeving te versterken`,
          threats: `Regeringsmeerderheid beperkt effectieve wijzigingscapaciteit${tf}${df} in commissies en Kamer`,
        },
        'private-sector': {
          strengths: `Domeinexpertise, operationele capaciteit en sectorspecifieke kennis${tf}${df} die beleidsontwerp beรฏnvloeden`,
          weaknesses: `Nalevingsaanpassingslast en regelgevende onzekerheid${tf}${df} die planningsuitdagingen creรซren`,
          opportunities: `Beleidsgedreven investeringen, innovatiepotentieel en marktontwikkeling${tf}${df}`,
          threats: `Snelle beleidsontwikkeling en korte implementatietijdlijnen${tf}${df} die concurrentieonzekerheid creรซren`,
        },
      }),
    },
    ar: {
      domainPrep: 'ููŠ ู…ุฌุงู„',
      builder: (tf, df) => ({
        government: {
          strengths: `ุงู„ุณู„ุทุฉ ุงู„ุชุดุฑูŠุนูŠุฉ ูˆู‚ุฏุฑุฉ ูˆุถุน ุงู„ุฃุฌู†ุฏุฉ ุงู„ุชู†ููŠุฐูŠุฉ${tf}${df} ู…ู† ุฎู„ุงู„ ู…ู‚ุชุฑุญุงุช ุงู„ุญูƒูˆู…ุฉ ูˆุงู„ุฃุฏูˆุงุช ุงู„ู‚ุงู†ูˆู†ูŠุฉ`,
          weaknesses: `ู…ุฎุงุทุฑ ุงู„ุชู†ููŠุฐ ูˆุชุญุฏูŠุงุช ุชุฎุตูŠุต ุงู„ู…ูˆุงุฑุฏ${tf}${df} ุงู„ุชูŠ ุชุชุทู„ุจ ุงู„ุชู†ุณูŠู‚ ุจูŠู† ุงู„ูˆูƒุงู„ุงุช`,
          opportunities: `ุงู„ุชูˆุงูู‚ ุงู„ุชู†ุธูŠู…ูŠ ู…ุน ุงู„ุงุชุญุงุฏ ุงู„ุฃูˆุฑูˆุจูŠ ูˆุฃุทุฑ ุงู„ุชุนุงูˆู† ุงู„ุฏูˆู„ูŠ${tf}${df} ู„ุชุทูˆูŠุฑ ุงู„ุณูŠุงุณุงุช`,
          threats: `ุฑู‚ุงุจุฉ ุงู„ู…ุนุงุฑุถุฉ ุงู„ุจุฑู„ู…ุงู†ูŠุฉ ูˆู…ุฎุงุทุฑ ุงู„ุชุนุฏูŠู„ ููŠ ุงู„ู„ุฌุงู†${tf}${df} ุงู„ุชูŠ ู‚ุฏ ุชุคุฎุฑ ุฃูˆ ุชุนุฏู„ ุงู„ู†ุชุงุฆุฌ ุงู„ุชุดุฑูŠุนูŠุฉ`,
        },
        parliament: {
          strengths: `ุชููˆูŠุถ ุงู„ุฑู‚ุงุจุฉ ูˆุงู„ุชุฏู‚ูŠู‚ ุนุจุฑ ุงู„ู„ุฌุงู†${tf}${df} ู…ู† ุฎู„ุงู„ ุงู„ุชู‚ุงุฑูŠุฑ ูˆุงู„ู…ู†ุงู‚ุดุงุช ุงู„ุจุฑู„ู…ุงู†ูŠุฉ`,
          weaknesses: `ุนุฏู… ุชู…ุงุซู„ ุงู„ู…ุนู„ูˆู…ุงุช ู…ู‚ุงุฑู†ุฉ ุจุงู„ุณู„ุทุฉ ุงู„ุชู†ููŠุฐูŠุฉ${tf}${df} ููŠ ุชูุงุตูŠู„ ุงู„ุชู†ููŠุฐ`,
          opportunities: `ุจู†ุงุก ุงู„ุชูˆุงูู‚ ุนุจุฑ ุงู„ุฃุญุฒุงุจ${tf}${df} ู„ุชุนุฒูŠุฒ ุงู„ุชุดุฑูŠุนุงุช`,
          threats: `ุงู„ุฃุบู„ุจูŠุฉ ุงู„ุญูƒูˆู…ูŠุฉ ุชุญุฏ ู…ู† ู‚ุฏุฑุฉ ุงู„ุชุนุฏูŠู„ ุงู„ูุนุงู„ุฉ${tf}${df} ููŠ ุงู„ู„ุฌุงู† ูˆุงู„ุฌู„ุณุงุช ุงู„ุนุงู…ุฉ`,
        },
        'private-sector': {
          strengths: `ุงู„ุฎุจุฑุฉ ุงู„ู‚ุทุงุนูŠุฉ ูˆุงู„ู‚ุฏุฑุฉ ุงู„ุชุดุบูŠู„ูŠุฉ ูˆุงู„ู…ุนุฑูุฉ ุงู„ู…ุชุฎุตุตุฉ${tf}${df} ุงู„ุชูŠ ุชุคุซุฑ ุนู„ู‰ ุชุตู…ูŠู… ุงู„ุณูŠุงุณุงุช`,
          weaknesses: `ุนุจุก ุงู„ุชูƒูŠู ู…ุน ุงู„ุงู…ุชุซุงู„ ูˆุนุฏู… ุงู„ูŠู‚ูŠู† ุงู„ุชู†ุธูŠู…ูŠ${tf}${df} ู…ู…ุง ูŠุฎู„ู‚ ุชุญุฏูŠุงุช ููŠ ุงู„ุชุฎุทูŠุท`,
          opportunities: `ุงุณุชุซู…ุงุฑ ู…ุฏููˆุน ุจุงู„ุณูŠุงุณุงุช ูˆุฅู…ูƒุงู†ุงุช ุงู„ุงุจุชูƒุงุฑ ูˆุชุทูˆูŠุฑ ุงู„ุณูˆู‚${tf}${df}`,
          threats: `ุชุทูˆุฑ ุณุฑูŠุน ู„ู„ุณูŠุงุณุงุช ูˆุฌุฏุงูˆู„ ุฒู…ู†ูŠุฉ ู‚ุตูŠุฑุฉ ู„ู„ุชู†ููŠุฐ${tf}${df} ุชุฎู„ู‚ ุนุฏู… ูŠู‚ูŠู† ุชู†ุงูุณูŠ`,
        },
      }),
    },
    he: {
      domainPrep: 'ื‘ืชื—ื•ื',
      builder: (tf, df) => ({
        government: {
          strengths: `ืกืžื›ื•ืช ื—ืงื™ืงื” ื•ื™ื›ื•ืœืช ืงื‘ื™ืขืช ืกื“ืจ ื™ื•ื ื‘ื™ืฆื•ืขื™${tf}${df} ื‘ืืžืฆืขื•ืช ื”ืฆืขื•ืช ืžืžืฉืœื” ื•ืžื›ืฉื™ืจื™ื ื—ื•ืงื™ื™ื`,
          weaknesses: `ืกื™ื›ื•ื ื™ ื™ื™ืฉื•ื ื•ืืชื’ืจื™ ื”ืงืฆืืช ืžืฉืื‘ื™ื${tf}${df} ื”ื“ื•ืจืฉื™ื ืชื™ืื•ื ื‘ื™ืŸ-ืžืฉืจื“ื™`,
          opportunities: `ื”ืชืืžื” ืœืจื’ื•ืœืฆื™ื” ืฉืœ ื”ืื™ื—ื•ื“ ื”ืื™ืจื•ืคื™ ื•ืžืกื’ืจื•ืช ืฉื™ืชื•ืฃ ืคืขื•ืœื” ื‘ื™ื ืœืื•ืžื™${tf}${df} ืœืงื™ื“ื•ื ืžื“ื™ื ื™ื•ืช`,
          threats: `ื‘ื™ืงื•ืจืช ืื•ืคื•ื–ื™ืฆื™ื” ืคืจืœืžื ื˜ืจื™ืช ื•ืกื™ื›ื•ื ื™ ืชื™ืงื•ืŸ ื‘ื•ื•ืขื“ื•ืช${tf}${df} ื”ืขืœื•ืœื™ื ืœืขื›ื‘ ืื• ืœืฉื ื•ืช ืชื•ืฆืื•ืช ื—ืงื™ืงื”`,
        },
        parliament: {
          strengths: `ืžื ื“ื˜ ืคื™ืงื•ื— ื•ื‘ื—ื™ื ื” ื—ื•ืฆืช-ื•ืขื“ื•ืช${tf}${df} ื‘ืืžืฆืขื•ืช ื“ื•ื—ื•ืช ื•ื“ื™ื•ื ื™ื ื‘ืžืœื™ืื”`,
          weaknesses: `ืื™-ืกื™ืžื˜ืจื™ื™ืช ืžื™ื“ืข ืžื•ืœ ื”ืจืฉื•ืช ื”ืžื‘ืฆืขืช${tf}${df} ื‘ืคืจื˜ื™ ื™ื™ืฉื•ื`,
          opportunities: `ื‘ื ื™ื™ืช ืงื•ื ืฆื ื–ื•ืก ื—ื•ืฆื”-ืžืคืœื’ื•ืช${tf}${df} ืœื—ื™ื–ื•ืง ื”ื—ืงื™ืงื”`,
          threats: `ืจื•ื‘ ืžืžืฉืœืชื™ ืžื’ื‘ื™ืœ ื™ื›ื•ืœืช ืชื™ืงื•ืŸ ืืคืงื˜ื™ื‘ื™ืช${tf}${df} ื‘ื•ื•ืขื“ื•ืช ื•ื‘ืžืœื™ืื”`,
        },
        'private-sector': {
          strengths: `ืžื•ืžื—ื™ื•ืช ืชื—ื•ืžื™ืช, ื™ื›ื•ืœืช ืชืคืขื•ืœื™ืช ื•ื™ื“ืข ืขื ืคื™-ืกืคืฆื™ืคื™${tf}${df} ื”ืžืฉืคื™ืขื™ื ืขืœ ืขื™ืฆื•ื‘ ืžื“ื™ื ื™ื•ืช`,
          weaknesses: `ื ื˜ืœ ื”ืชืืžื” ืœืฆื™ื•ืช ื•ืื™-ื•ื“ืื•ืช ืจื’ื•ืœื˜ื•ืจื™ืช${tf}${df} ื”ื™ื•ืฆืจื™ื ืืชื’ืจื™ ืชื›ื ื•ืŸ`,
          opportunities: `ื”ืฉืงืขื” ืžื•ื ืขืช-ืžื“ื™ื ื™ื•ืช, ืคื•ื˜ื ืฆื™ืืœ ื—ื“ืฉื ื•ืช ื•ืคื™ืชื•ื— ืฉื•ืง${tf}${df}`,
          threats: `ื”ืชืคืชื—ื•ืช ืžื”ื™ืจื” ืฉืœ ืžื“ื™ื ื™ื•ืช ื•ืœื•ื—ื•ืช ื–ืžื ื™ื ืงืฆืจื™ื ืœื™ื™ืฉื•ื${tf}${df} ื™ื•ืฆืจื™ื ืื™-ื•ื“ืื•ืช ืชื—ืจื•ืชื™ืช`,
        },
      }),
    },
    ja: {
      domainPrep: 'ใฎๅˆ†้‡ŽใซใŠใ‘ใ‚‹',
      builder: (tf, df) => ({
        government: {
          strengths: `็ซ‹ๆณ•ๆจฉ้™ใจ่กŒๆ”ฟใ‚ขใ‚ธใ‚งใƒณใƒ€่จญๅฎš่ƒฝๅŠ›${tf}${df}๏ผˆๆ”ฟๅบœๆๆกˆใจๆณ•็š„ๆ‰‹ๆฎตใ‚’้€šใ˜ใฆ๏ผ‰`,
          weaknesses: `ๅฎŸๆ–ฝใƒชใ‚นใ‚ฏใจใƒชใ‚ฝใƒผใ‚น้…ๅˆ†ใฎ่ชฒ้กŒ${tf}${df}๏ผˆ็œๅบ้–“ใฎ่ชฟๆ•ดใŒๅฟ…่ฆ๏ผ‰`,
          opportunities: `EU่ฆๅˆถใฎๆ•ดๅˆๆ€งใจๅ›ฝ้š›ๅ”ๅŠ›ใฎๆž ็ต„ใฟ${tf}${df}๏ผˆๆ”ฟ็ญ–ๆŽจ้€ฒใฎใŸใ‚๏ผ‰`,
          threats: `่ญฐไผš้‡Žๅ…šใฎ็›ฃ่ฆ–ใจๅง”ๅ“กไผšไฟฎๆญฃใƒชใ‚นใ‚ฏ${tf}${df}๏ผˆ็ซ‹ๆณ•ๆˆๆžœใ‚’้…ๅปถใƒปไฟฎๆญฃใ™ใ‚‹ๅฏ่ƒฝๆ€ง๏ผ‰`,
        },
        parliament: {
          strengths: `็›ฃ่ฆ–ๆจฉ้™ใจๅง”ๅ“กไผšๆจชๆ–ญ็š„ๅฏฉๆŸป${tf}${df}๏ผˆๅ ฑๅ‘Šๆ›ธใจๆœฌไผš่ญฐ่จŽ่ซ–ใ‚’้€šใ˜ใฆ๏ผ‰`,
          weaknesses: `่กŒๆ”ฟๅบœใซๅฏพใ™ใ‚‹ๆƒ…ๅ ฑใฎ้žๅฏพ็งฐๆ€ง${tf}${df}๏ผˆๅฎŸๆ–ฝ่ฉณ็ดฐใซใคใ„ใฆ๏ผ‰`,
          opportunities: `ๅ…šๆดพใ‚’่ถ…ใˆใŸๅˆๆ„ๅฝขๆˆ${tf}${df}๏ผˆ็ซ‹ๆณ•ใ‚’ๅผทๅŒ–ใ™ใ‚‹ใŸใ‚๏ผ‰`,
          threats: `ๆ”ฟๅบœๅคšๆ•ฐๆดพใŒๆœ‰ๅŠนใชไฟฎๆญฃ่ƒฝๅŠ›ใ‚’ๅˆถ้™${tf}${df}๏ผˆๅง”ๅ“กไผšใจๆœฌไผš่ญฐใง๏ผ‰`,
        },
        'private-sector': {
          strengths: `ๅฐ‚้–€็Ÿฅ่ญ˜ใ€้‹ๅ–ถ่ƒฝๅŠ›ใ€ๆฅญ็•Œๅ›บๆœ‰ใฎ็Ÿฅ่ญ˜${tf}${df}๏ผˆๆ”ฟ็ญ–่จญ่จˆใซๅฝฑ้Ÿฟ๏ผ‰`,
          weaknesses: `ใ‚ณใƒณใƒ—ใƒฉใ‚คใ‚ขใƒณใ‚น้ฉๅฟœ่ฒ ๆ‹…ใจ่ฆๅˆถใฎไธ็ขบๅฎŸๆ€ง${tf}${df}๏ผˆ่จˆ็”ปไธŠใฎ่ชฒ้กŒใ‚’็”Ÿๆˆ๏ผ‰`,
          opportunities: `ๆ”ฟ็ญ–ไธปๅฐŽใฎๆŠ•่ณ‡ใ€ใ‚คใƒŽใƒ™ใƒผใ‚ทใƒงใƒณๅฏ่ƒฝๆ€งใ€ๅธ‚ๅ ด้–‹็™บ${tf}${df}`,
          threats: `ๆ€ฅ้€Ÿใชๆ”ฟ็ญ–ๅฑ•้–‹ใจ็Ÿญใ„ๅฎŸๆ–ฝๆœŸ้™${tf}${df}๏ผˆ็ซถไบ‰ไธŠใฎไธ็ขบๅฎŸๆ€งใ‚’็”Ÿๆˆ๏ผ‰`,
        },
      }),
    },
    ko: {
      domainPrep: '๋ถ„์•ผ์—์„œ',
      builder: (tf, df) => ({
        government: {
          strengths: `์ž…๋ฒ• ๊ถŒํ•œ๊ณผ ํ–‰์ •๋ถ€ ์˜์ œ ์„ค์ • ์—ญ๋Ÿ‰${tf}${df} (์ •๋ถ€ ์ œ์•ˆ๊ณผ ๋ฒ•์  ์ˆ˜๋‹จ์„ ํ†ตํ•ด)`,
          weaknesses: `์‹œํ–‰ ๋ฆฌ์Šคํฌ์™€ ์ž์› ๋ฐฐ๋ถ„ ๊ณผ์ œ${tf}${df} (๋ถ€์ฒ˜ ๊ฐ„ ์กฐ์ • ํ•„์š”)`,
          opportunities: `EU ๊ทœ์ œ ์กฐํ™”์™€ ๊ตญ์ œ ํ˜‘๋ ฅ ์ฒด๊ณ„${tf}${df} (์ •์ฑ… ๋ฐœ์ „์„ ์œ„ํ•ด)`,
          threats: `์˜ํšŒ ์•ผ๋‹น ๊ฐ์‹œ์™€ ์œ„์›ํšŒ ์ˆ˜์ • ๋ฆฌ์Šคํฌ${tf}${df} (์ž…๋ฒ• ๊ฒฐ๊ณผ๋ฅผ ์ง€์—ฐ ๋˜๋Š” ๋ณ€๊ฒฝ ๊ฐ€๋Šฅ)`,
        },
        parliament: {
          strengths: `๊ฐ๋… ๊ถŒํ•œ๊ณผ ์œ„์›ํšŒ ๊ฐ„ ์‹ฌ์‚ฌ${tf}${df} (๋ณด๊ณ ์„œ์™€ ๋ณธํšŒ์˜ ํ† ๋ก ์„ ํ†ตํ•ด)`,
          weaknesses: `ํ–‰์ •๋ถ€์— ๋Œ€ํ•œ ์ •๋ณด ๋น„๋Œ€์นญ${tf}${df} (์‹œํ–‰ ์„ธ๋ถ€์‚ฌํ•ญ์— ๋Œ€ํ•ด)`,
          opportunities: `์ดˆ๋‹น์  ํ•ฉ์˜ ํ˜•์„ฑ${tf}${df} (์ž…๋ฒ• ๊ฐ•ํ™”๋ฅผ ์œ„ํ•ด)`,
          threats: `์ •๋ถ€ ๋‹ค์ˆ˜๋‹น์ด ํšจ๊ณผ์  ์ˆ˜์ • ์—ญ๋Ÿ‰์„ ์ œํ•œ${tf}${df} (์œ„์›ํšŒ์™€ ๋ณธํšŒ์˜์—์„œ)`,
        },
        'private-sector': {
          strengths: `์ „๋ฌธ ์ง€์‹, ์šด์˜ ์—ญ๋Ÿ‰, ์—…์ข…๋ณ„ ์ง€์‹${tf}${df} (์ •์ฑ… ์„ค๊ณ„์— ์˜ํ–ฅ)`,
          weaknesses: `์ปดํ”Œ๋ผ์ด์–ธ์Šค ์ ์‘ ๋ถ€๋‹ด๊ณผ ๊ทœ์ œ ๋ถˆํ™•์‹ค์„ฑ${tf}${df} (๊ณ„ํš ์ˆ˜๋ฆฝ ๊ณผ์ œ ์•ผ๊ธฐ)`,
          opportunities: `์ •์ฑ… ์ฃผ๋„ ํˆฌ์ž, ํ˜์‹  ์ž ์žฌ๋ ฅ, ์‹œ์žฅ ๊ฐœ๋ฐœ${tf}${df}`,
          threats: `๋น ๋ฅธ ์ •์ฑ… ๋ณ€ํ™”์™€ ์งง์€ ์‹œํ–‰ ๊ธฐํ•œ${tf}${df} (๊ฒฝ์Ÿ ๋ถˆํ™•์‹ค์„ฑ ์•ผ๊ธฐ)`,
        },
      }),
    },
    zh: {
      domainPrep: '้ข†ๅŸŸ',
      builder: (tf, df) => ({
        government: {
          strengths: `็ซ‹ๆณ•ๆƒๅŠ›ๅ’Œ่กŒๆ”ฟ่ฎฎ็จ‹่ฎพๅฎš่ƒฝๅŠ›${tf}${df}๏ผˆ้€š่ฟ‡ๆ”ฟๅบœๆๆกˆๅ’Œๆณ•ๅพ‹ๆ–‡ไนฆ๏ผ‰`,
          weaknesses: `ๅฎžๆ–ฝ้ฃŽ้™ฉๅ’Œ่ต„ๆบๅˆ†้…ๆŒ‘ๆˆ˜${tf}${df}๏ผˆ้œ€่ฆ่ทจ้ƒจ้—จๅ่ฐƒ๏ผ‰`,
          opportunities: `ๆฌง็›Ÿ็›‘็ฎกๅ่ฐƒๅ’Œๅ›ฝ้™…ๅˆไฝœๆก†ๆžถ${tf}${df}๏ผˆๆŽจๅŠจๆ”ฟ็ญ–ๅ‘ๅฑ•๏ผ‰`,
          threats: `่ฎฎไผšๅๅฏนๆดพๅฎกๆŸฅๅ’Œๅง”ๅ‘˜ไผšไฟฎๆ”น้ฃŽ้™ฉ${tf}${df}๏ผˆๅฏ่ƒฝๅปถ่ฟŸๆˆ–ไฟฎๆ”น็ซ‹ๆณ•ๆˆๆžœ๏ผ‰`,
        },
        parliament: {
          strengths: `็›‘็ฃๆƒ้™ๅ’Œ่ทจๅง”ๅ‘˜ไผšๅฎกๆŸฅ${tf}${df}๏ผˆ้€š่ฟ‡ๆŠฅๅ‘Šๅ’Œๅ…จไฝ“ไผš่ฎฎ่พฉ่ฎบ๏ผ‰`,
          weaknesses: `็›ธๅฏน่กŒๆ”ฟ้ƒจ้—จ็š„ไฟกๆฏไธๅฏน็งฐ${tf}${df}๏ผˆๅœจๅฎžๆ–ฝ็ป†่Š‚ๆ–น้ข๏ผ‰`,
          opportunities: `่ทจๅ…šๆดพๅ…ฑ่ฏ†ๆž„ๅปบ${tf}${df}๏ผˆๅŠ ๅผบ็ซ‹ๆณ•๏ผ‰`,
          threats: `ๆ”ฟๅบœๅคšๆ•ฐ้™ๅˆถๆœ‰ๆ•ˆไฟฎๆ”น่ƒฝๅŠ›${tf}${df}๏ผˆๅœจๅง”ๅ‘˜ไผšๅ’Œๅ…จไฝ“ไผš่ฎฎไธญ๏ผ‰`,
        },
        'private-sector': {
          strengths: `้ข†ๅŸŸไธ“้•ฟใ€่ฟ่ฅ่ƒฝๅŠ›ๅ’Œ่กŒไธšไธ“ไธš็Ÿฅ่ฏ†${tf}${df}๏ผˆๅฝฑๅ“ๆ”ฟ็ญ–่ฎพ่ฎก๏ผ‰`,
          weaknesses: `ๅˆ่ง„้€‚ๅบ”่ดŸๆ‹…ๅ’Œ็›‘็ฎกไธ็กฎๅฎšๆ€ง${tf}${df}๏ผˆ้€ ๆˆ่ง„ๅˆ’ๆŒ‘ๆˆ˜๏ผ‰`,
          opportunities: `ๆ”ฟ็ญ–้ฉฑๅŠจๆŠ•่ต„ใ€ๅˆ›ๆ–ฐๆฝœๅŠ›ๅ’Œๅธ‚ๅœบๅ‘ๅฑ•${tf}${df}`,
          threats: `ๅฟซ้€Ÿๆ”ฟ็ญ–ๆผ”ๅ˜ๅ’Œ็ดง่ฟซ็š„ๅฎžๆ–ฝๆ—ถ้—ด่กจ${tf}${df}๏ผˆ้€ ๆˆ็ซžไบ‰ไธ็กฎๅฎšๆ€ง๏ผ‰`,
        },
      }),
    },
};
 
/**
 * Apply language-specific framing to a placeholder text.
 * Provides localised SWOT placeholder compositions for all 14 supported languages
 * so non-English articles render in their target language.
 */
function applyLanguageFraming(
  enText: string,
  lang: Language,
  role: string,
  quadrant: string,
  topic: string | null,
  domain: string | null,
): string {
  if (lang === 'en') return enText;
 
  const entry = SWOT_LANGUAGE_BUILDERS[lang];
  if (entry) {
    const topicFrag = topic ? ` (${topic})` : '';
    const domainFrag = domain ? ` ${entry.domainPrep} ${domain}` : '';
    const compositions = entry.builder(topicFrag, domainFrag);
    const roleComposition = compositions[role] ?? compositions['government']!;
    const text = roleComposition[quadrant];
    if (text) return text;
  }
 
  // Fallback to English for any unlisted language
  return enText;
}
 
// ---------------------------------------------------------------------------
// Policy assessment builder
// ---------------------------------------------------------------------------
 
function buildPolicyAssessment(
  docs: RawDocument[],
  topic: string | null,
  lang: Language,
): PolicyAssessment {
  const allDomains = new Set<string>();
  docs.forEach(d => detectPolicyDomains(d, lang).forEach(dom => allDomains.add(dom)));
  const domains = [...allDomains].slice(0, 8);
  const primaryDomain = domains[0] ?? null;
 
  const metadataEnrichedCount = docs.filter(isMetadataEnriched).length;
  const fullTextCount = docs.filter(hasFullTextContent).length;
  // Confidence baseline: 40 (raw metadata), 60 (metadata-enriched), 80 (full-text available)
  const baseConfidence = fullTextCount > 0 ? 80 : metadataEnrichedCount > 0 ? 60 : 40;
  const confidence = assessConfidenceLevel(docs.length, baseConfidence);
 
  // Build a narrative from available evidence โ€” topic + primary domain + document count
  // Use "full text" wording only when fullTextCount > 0; fall back to "metadata" wording
  const docsLabelFn = DASHBOARD_DOCS_ANALYSED[lang] ?? DASHBOARD_DOCS_ANALYSED.en!;
  let evidenceDesc: string;
  if (fullTextCount > 0) {
    const fullTextFn = NARRATIVE_WITH_FULL_TEXT[lang] ?? NARRATIVE_WITH_FULL_TEXT.en!;
    evidenceDesc = fullTextFn(docs.length, fullTextCount);
  } else if (metadataEnrichedCount > 0) {
    const metadataFn = NARRATIVE_WITH_METADATA[lang] ?? NARRATIVE_WITH_METADATA.en!;
    evidenceDesc = metadataFn(docs.length, metadataEnrichedCount);
  } else {
    evidenceDesc = docsLabelFn(docs.length);
  }
 
  const analysisOf = NARRATIVE_ANALYSIS_OF[lang] ?? NARRATIVE_ANALYSIS_OF.en!;
  const reveals = NARRATIVE_REVEALS[lang] ?? NARRATIVE_REVEALS.en!;
  const policyActivity = NARRATIVE_POLICY_ACTIVITY[lang] ?? NARRATIVE_POLICY_ACTIVITY.en!;
  const parlActivity = NARRATIVE_PARLIAMENTARY_ACTIVITY[lang] ?? NARRATIVE_PARLIAMENTARY_ACTIVITY.en!;
  const focusLabel = NARRATIVE_FOCUS[lang] ?? NARRATIVE_FOCUS.en!;
 
  const domainList = domains.slice(0, 3).join(', ');
  const activityPhrase = domains.length > 0
    ? `${policyActivity} ${domainList}`
    : parlActivity;
  const topicPhrase = topic ? ` ${focusLabel} ${topic}` : '';
  const narrative = `${analysisOf} ${evidenceDesc} ${reveals} ${activityPhrase}${topicPhrase}.`;
 
  return { domains, primaryDomain, narrative, confidence };
}
 
// ---------------------------------------------------------------------------
// Watch point builder
// ---------------------------------------------------------------------------
 
function buildWatchPoints(
  docs: RawDocument[],
  topic: string | null,
  lang: Language,
): AnalysisWatchPoint[] {
  const points: AnalysisWatchPoint[] = [];
 
  const propDocs = docs.filter(d => docType(d) === 'prop');
  const betDocs  = docs.filter(d => docType(d) === 'bet');
  const motDocs  = docs.filter(d => docType(d) === 'mot');
  const sfsDocs  = docs.filter(isSfsDoc);
  const euDocs   = docs.filter(d => docType(d) === 'fpm' || docType(d) === 'eu');
 
  const topicSuffix = topic ? ` (${topic})` : '';
 
  if (propDocs.length > 0) {
    const titles = propDocs.slice(0, 2).map(d => docTitle(d)).join('; ');
    const descFn = WP_PROPS_DESC[lang] ?? WP_PROPS_DESC.en!;
    points.push({
      title: `${WP_ACTIVE_PROPS[lang] ?? WP_ACTIVE_PROPS.en!}${topicSuffix}`,
      description: `${descFn(propDocs.length)}: ${titles}`,
      urgency: 'high',
      sourceDocIds: propDocs.map(docId).filter(Boolean),
    });
  }
 
  if (betDocs.length > 0) {
    const descFn = WP_COMMITTEE_DESC[lang] ?? WP_COMMITTEE_DESC.en!;
    points.push({
      title: `${WP_COMMITTEE[lang] ?? WP_COMMITTEE.en!}${topicSuffix}`,
      description: `${descFn(betDocs.length)}${topicSuffix}`,
      urgency: 'high',
      sourceDocIds: betDocs.map(docId).filter(Boolean),
    });
  }
 
  if (sfsDocs.length > 0) {
    const descFn = WP_SFS_DESC[lang] ?? WP_SFS_DESC.en!;
    points.push({
      title: `${WP_SFS[lang] ?? WP_SFS.en!}${topicSuffix}`,
      description: descFn(sfsDocs.length),
      urgency: 'critical',
      sourceDocIds: sfsDocs.map(docId).filter(Boolean),
    });
  }
 
  if (motDocs.length > 0) {
    const descFn = WP_MOTIONS_DESC[lang] ?? WP_MOTIONS_DESC.en!;
    points.push({
      title: `${WP_MOTIONS[lang] ?? WP_MOTIONS.en!}${topicSuffix}`,
      description: `${descFn(motDocs.length)}${topicSuffix}`,
      urgency: 'medium',
      sourceDocIds: motDocs.map(docId).filter(Boolean),
    });
  }
 
  if (euDocs.length > 0) {
    const descFn = WP_EU_DESC[lang] ?? WP_EU_DESC.en!;
    points.push({
      title: `${WP_EU[lang] ?? WP_EU.en!}${topicSuffix}`,
      description: descFn(euDocs.length),
      urgency: 'medium',
      sourceDocIds: euDocs.map(docId).filter(Boolean),
    });
  }
 
  // Detect narrative frames for additional watch points
  const allFrames = new Set<string>();
  docs.slice(0, 10).forEach(d => detectNarrativeFrames(d).forEach(f => allFrames.add(f)));
  if (allFrames.size > 0) {
    const frameList = [...allFrames].slice(0, 3).join(', ');
    points.push({
      title: WP_NARRATIVE[lang] ?? WP_NARRATIVE.en!,
      description: `${WP_NARRATIVE_DESC[lang] ?? WP_NARRATIVE_DESC.en!}${frameList}`,
      urgency: 'low',
      sourceDocIds: [],
    });
  }
 
  return points;
}
 
// ---------------------------------------------------------------------------
// Mindmap branch builder
// ---------------------------------------------------------------------------
 
function buildMindmapBranches(
  docs: RawDocument[],
  topic: string | null,
  domains: string[],
  lang: Language,
): AnalysisMindmapBranch[] {
  const branches: AnalysisMindmapBranch[] = [];
 
  // Document type branch
  const typeCounts: Record<string, number> = {};
  docs.forEach(d => {
    const t = normalizedDocType(d);
    typeCounts[t] = (typeCounts[t] || 0) + 1;
  });
  const typeKeys = Object.keys(typeCounts);
  if (typeKeys.length > 0) {
    branches.push({
      label: docTypesLabel(lang),
      color: 'cyan',
      icon: '๐Ÿ“„',
      items: typeKeys.map(t => `${localizeDocType(t, lang, typeCounts[t] ?? 0)} (${typeCounts[t] ?? 0})`),
    });
  }
 
  // Policy domains branch
  if (domains.length > 0) {
    branches.push({
      label: policyDomainsLabel(lang),
      color: 'green',
      icon: '๐Ÿ›๏ธ',
      items: domains,
    });
  }
 
  // Stakeholder branch
  branches.push({
    label: stakeholdersLabel(lang),
    color: 'yellow',
    icon: '๐Ÿ‘ฅ',
    items: [
      GOV_NAMES[lang] ?? GOV_NAMES.en!,
      OPP_NAMES[lang] ?? OPP_NAMES.en!,
      PRIVATE_NAMES[lang] ?? PRIVATE_NAMES.en!,
    ],
  });
 
  // Data sources branch
  branches.push({
    label: DATA_SOURCE_LABELS[lang] ?? DATA_SOURCE_LABELS.en!,
    color: 'purple',
    icon: '๐Ÿ“Š',
    items: DATA_SOURCE_ITEMS[lang] ?? DATA_SOURCE_ITEMS.en!,
  });
 
  // Topic-derived focus branch (only when topic is provided)
  if (topic) {
    const allFrames = new Set<string>();
    docs.slice(0, 15).forEach(d => detectNarrativeFrames(d).forEach(f => allFrames.add(f)));
    if (allFrames.size > 0) {
      branches.push({
        label: narrativeFramesLabel(lang),
        color: 'orange',
        icon: '๐ŸŽฏ',
        items: [...allFrames].slice(0, 6),
      });
    }
  }
 
  return branches;
}
 
// Localised section labels
function docTypesLabel(lang: Language): string {
  const m: LangRecord = { en: 'Document Types', sv: 'Dokumenttyper', da: 'Dokumenttyper', no: 'Dokumenttyper', fi: 'Asiakirjatyypit', de: 'Dokumenttypen', fr: 'Types de documents', es: 'Tipos de documentos', nl: 'Documenttypen', ar: 'ุฃู†ูˆุงุน ุงู„ูˆุซุงุฆู‚', he: 'ืกื•ื’ื™ ืžืกืžื›ื™ื', ja: 'ๆ–‡ๆ›ธ็จฎ้กž', ko: '๋ฌธ์„œ ์œ ํ˜•', zh: 'ๆ–‡ไปถ็ฑปๅž‹' };
  return m[lang] ?? m.en!;
}
function policyDomainsLabel(lang: Language): string {
  const m: LangRecord = { en: 'Policy Domains', sv: 'Politikomrรฅden', da: 'Politikomrรฅder', no: 'Politikkomrรฅder', fi: 'Politiikka-alueet', de: 'Politikbereiche', fr: 'Domaines politiques', es: 'รreas de polรญtica', nl: 'Beleidsdomeinen', ar: 'ู…ุฌุงู„ุงุช ุงู„ุณูŠุงุณุฉ', he: 'ืชื—ื•ืžื™ ืžื“ื™ื ื™ื•ืช', ja: 'ๆ”ฟ็ญ–ๅˆ†้‡Ž', ko: '์ •์ฑ… ์˜์—ญ', zh: 'ๆ”ฟ็ญ–้ข†ๅŸŸ' };
  return m[lang] ?? m.en!;
}
function stakeholdersLabel(lang: Language): string {
  const m: LangRecord = { en: 'Stakeholders', sv: 'Intressenter', da: 'Interessenter', no: 'Interessenter', fi: 'Sidosryhmรคt', de: 'Stakeholder', fr: 'Parties prenantes', es: 'Partes interesadas', nl: 'Belanghebbenden', ar: 'ุฃุตุญุงุจ ุงู„ู…ุตู„ุญุฉ', he: 'ื‘ืขืœื™ ืขื ื™ื™ืŸ', ja: 'ใ‚นใƒ†ใƒผใ‚ฏใƒ›ใƒซใƒ€ใƒผ', ko: '์ดํ•ด๊ด€๊ณ„์ž', zh: 'ๅˆฉ็›Š็›ธๅ…ณ่€…' };
  return m[lang] ?? m.en!;
}
function narrativeFramesLabel(lang: Language): string {
  const m: LangRecord = { en: 'Narrative Frames', sv: 'Narrativa ramar', da: 'Narrative rammer', no: 'Narrative rammer', fi: 'Narratiiviset kehykset', de: 'Narrative Rahmen', fr: 'Cadres narratifs', es: 'Marcos narrativos', nl: 'Narratieve frames', ar: 'ุงู„ุฅุทุงุฑุงุช ุงู„ุณุฑุฏูŠุฉ', he: 'ืžืกื’ืจื•ืช ื ืจื˜ื™ื‘ื™ื•ืช', ja: '็‰ฉ่ชžใƒ•ใƒฌใƒผใƒ ', ko: '์„œ์‚ฌ ํ”„๋ ˆ์ž„', zh: 'ๅ™ไบ‹ๆก†ๆžถ' };
  return m[lang] ?? m.en!;
}
 
// ---------------------------------------------------------------------------
// Dashboard data builder
// ---------------------------------------------------------------------------
 
function buildDashboardData(
  docs: RawDocument[],
  topic: string | null,
  lang: Language,
): DashboardData {
  const typeCounts: Record<string, number> = {};
  docs.forEach(d => {
    const t = normalizedDocType(d);
    typeCounts[t] = (typeCounts[t] || 0) + 1;
  });
 
  const typeKeys = Object.keys(typeCounts);
  const typeDistribution = typeKeys.map((t, i) => ({
    label: localizeDocType(t, lang, typeCounts[t] ?? 0),
    value: typeCounts[t] ?? 0,
    color: TYPE_PALETTE[i % TYPE_PALETTE.length] ?? '#00d9ff',
  }));
 
  const docIntelLabel = DASHBOARD_TITLE[lang] ?? DASHBOARD_TITLE.en!;
  const title = topic ? `${docIntelLabel} โ€” ${topic}` : docIntelLabel;
  const docsAnalysedFn = DASHBOARD_DOCS_ANALYSED[lang] ?? DASHBOARD_DOCS_ANALYSED.en!;
  const summary = docsAnalysedFn(docs.length);
 
  return { title, summary, typeDistribution };
}
 
// ---------------------------------------------------------------------------
// Confidence score calculator
// ---------------------------------------------------------------------------
 
function calculateConfidenceScore(docs: RawDocument[]): number {
  if (docs.length === 0) return 0;
  const metadataEnriched = docs.filter(isMetadataEnriched).length;
  const fullText = docs.filter(hasFullTextContent).length;
  const typeVariety = new Set(docs.map(normalizedDocType)).size;
  // Score: 0-100, split across three dimensions:
  // - Enrichment (total 50%): metadata-enriched (30%) + full-text (20%)
  // - Document count (up to 10): 30%
  // - Type variety (up to 5): 20%
  const metadataRatio = metadataEnriched / docs.length;
  const fullTextRatio = fullText / docs.length;
  const enrichmentScore = metadataRatio * 30 + fullTextRatio * 20;
  const countScore = Math.min(docs.length / 10, 1) * 30;
  const varietyScore = Math.min(typeVariety / 5, 1) * 20;
  return Math.round(enrichmentScore + countScore + varietyScore);
}
 
// ---------------------------------------------------------------------------
// Iteration 1: analyzeDocuments
// ---------------------------------------------------------------------------
 
async function analyzeDocuments(
  docs: RawDocument[],
  options: AnalysisPipelineOptions,
): Promise<AnalysisResult> {
  const { lang, focusTopic: topic } = options;
 
  const domains = (() => {
    const all = new Set<string>();
    docs.forEach(d => detectPolicyDomains(d, lang).forEach(dom => all.add(dom)));
    return [...all].slice(0, 8);
  })();
 
  // Classify documents by type
  const propDocs    = docs.filter(d => docType(d) === 'prop');
  const betDocs     = docs.filter(d => docType(d) === 'bet');
  const motDocs     = docs.filter(d => docType(d) === 'mot');
  const skrDocs     = docs.filter(d => docType(d) === 'skr');
  const sfsDocs     = docs.filter(isSfsDoc);
  const euDocs      = docs.filter(d => docType(d) === 'fpm' || docType(d) === 'eu');
  const pressmDocs  = docs.filter(d => docType(d) === 'pressm');
  const extDocs     = docs.filter(d => docType(d) === 'ext');
 
  // โ”€โ”€ Government stakeholder SWOT โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  const govStrengths: AnalysisSwotEntry[] = [
    ...propDocs.slice(0, 3).map(d => buildEnrichedEntry(d, topic, lang, 200)),
    ...sfsDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, 200)),
    ...skrDocs.slice(0, 1).map(d => buildEnrichedEntry(d, topic, lang, 200)),
    ...pressmDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, 200)),
  ];
  const govWeaknesses: AnalysisSwotEntry[] = [
    ...betDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, 200)),
  ];
  const govOpportunities: AnalysisSwotEntry[] = [
    ...euDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, 200)),
    ...skrDocs.slice(1, 2).map(d => buildEnrichedEntry(d, topic, lang, 200)),
  ];
  const govThreats: AnalysisSwotEntry[] = [
    ...motDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, 200)),
  ];
 
  if (govStrengths.length === 0)    govStrengths.push(placeholderEntry('government', 'strengths', topic, lang, domains));
  if (govWeaknesses.length === 0)   govWeaknesses.push(placeholderEntry('government', 'weaknesses', topic, lang, domains));
  if (govOpportunities.length === 0) govOpportunities.push(placeholderEntry('government', 'opportunities', topic, lang, domains));
  if (govThreats.length === 0)      govThreats.push(placeholderEntry('government', 'threats', topic, lang, domains));
 
  // โ”€โ”€ Parliament / Opposition SWOT โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  const oppStrengths: AnalysisSwotEntry[] = [
    ...betDocs.slice(0, 3).map(d => buildEnrichedEntry(d, topic, lang, 200)),
    ...motDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, 200)),
  ];
  const oppWeaknesses: AnalysisSwotEntry[] = [];
  const oppOpportunities: AnalysisSwotEntry[] = [];
  const oppThreats: AnalysisSwotEntry[] = [
    ...propDocs.slice(0, 1).map(d => buildEnrichedEntry(d, topic, lang, 200)),
  ];
 
  if (oppStrengths.length === 0)    oppStrengths.push(placeholderEntry('parliament', 'strengths', topic, lang, domains));
  if (oppWeaknesses.length === 0)   oppWeaknesses.push(placeholderEntry('parliament', 'weaknesses', topic, lang, domains));
  if (oppOpportunities.length === 0) oppOpportunities.push(placeholderEntry('parliament', 'opportunities', topic, lang, domains));
  if (oppThreats.length === 0)      oppThreats.push(placeholderEntry('parliament', 'threats', topic, lang, domains));
 
  // โ”€โ”€ Private Sector / Civil Society SWOT โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  const privateStrengths: AnalysisSwotEntry[] = [
    ...sfsDocs.slice(0, 1).map(d => buildEnrichedEntry(d, topic, lang, 200)),
    ...extDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, 200)),
  ];
  const privateWeaknesses: AnalysisSwotEntry[] = [];
  const privateOpportunities: AnalysisSwotEntry[] = [
    ...euDocs.slice(0, 1).map(d => buildEnrichedEntry(d, topic, lang, 200)),
  ];
  const privateThreats: AnalysisSwotEntry[] = [];
 
  if (privateStrengths.length === 0)    privateStrengths.push(placeholderEntry('private-sector', 'strengths', topic, lang, domains));
  if (privateWeaknesses.length === 0)   privateWeaknesses.push(placeholderEntry('private-sector', 'weaknesses', topic, lang, domains));
  if (privateOpportunities.length === 0) privateOpportunities.push(placeholderEntry('private-sector', 'opportunities', topic, lang, domains));
  if (privateThreats.length === 0)      privateThreats.push(placeholderEntry('private-sector', 'threats', topic, lang, domains));
 
  // Assemble stakeholder SWOT list
  const stakeholderSwot: AnalysisStakeholderSwot[] = [
    {
      name: GOV_NAMES[lang] ?? GOV_NAMES.en!,
      role: 'government',
      swot: { strengths: govStrengths, weaknesses: govWeaknesses, opportunities: govOpportunities, threats: govThreats },
    },
    {
      name: OPP_NAMES[lang] ?? OPP_NAMES.en!,
      role: 'parliament',
      swot: { strengths: oppStrengths, weaknesses: oppWeaknesses, opportunities: oppOpportunities, threats: oppThreats },
    },
    {
      name: PRIVATE_NAMES[lang] ?? PRIVATE_NAMES.en!,
      role: 'private-sector',
      swot: { strengths: privateStrengths, weaknesses: privateWeaknesses, opportunities: privateOpportunities, threats: privateThreats },
    },
  ];
 
  const policyAssessment = buildPolicyAssessment(docs, topic, lang);
  const watchPoints = buildWatchPoints(docs, topic, lang);
  const mindmapBranches = buildMindmapBranches(docs, topic, policyAssessment.domains, lang);
  const dashboardData = buildDashboardData(docs, topic, lang);
  const confidenceScore = calculateConfidenceScore(docs);
 
  return {
    stakeholderSwot,
    policyAssessment,
    mindmapBranches,
    dashboardData,
    watchPoints,
    confidenceScore,
    iterationsCompleted: 1,
    completedAt: new Date().toISOString(),
    lang,
    documentCount: docs.length,
    enrichedCount: docs.filter(isMetadataEnriched).length,
    focusTopic: topic,
  };
}
 
// ---------------------------------------------------------------------------
// Iteration 2: refineAnalysis
// ---------------------------------------------------------------------------
 
async function refineAnalysis(
  initial: AnalysisResult,
  docs: RawDocument[],
  options: AnalysisPipelineOptions,
): Promise<AnalysisResult> {
  const { lang, focusTopic: topic } = options;
  const fullTextDocs = docs.filter(hasFullTextContent);
 
  // Update enrichedCount to reflect metadata enrichment (may be > 0 even
  // when no full-text documents are available โ€” the typical Riksdag case).
  const metadataCount = docs.filter(isMetadataEnriched).length;
 
  if (fullTextDocs.length === 0) {
    // No documents with full text/content available โ€” passage-based refinement
    // is a no-op.  This is expected when enrichDocumentsWithContent() fetches
    // metadata only (include_full_text=false).  We still bump
    // iterationsCompleted to 2 so the pipeline contract is honoured, and
    // update enrichedCount to reflect the metadata-enriched population.
    return { ...initial, iterationsCompleted: 2, completedAt: new Date().toISOString(), enrichedCount: metadataCount };
  }
 
  // Re-derive SWOT entries with longer passages for enriched documents
  const passageMax = 400;
  const refined = { ...initial, iterationsCompleted: 2, completedAt: new Date().toISOString() };
 
  // Rebuild stakeholder SWOT with richer content from enriched documents
  const propDocs   = fullTextDocs.filter(d => docType(d) === 'prop');
  const betDocs    = fullTextDocs.filter(d => docType(d) === 'bet');
  const motDocs    = fullTextDocs.filter(d => docType(d) === 'mot');
  const sfsDocs    = fullTextDocs.filter(isSfsDoc);
  const euDocs     = fullTextDocs.filter(d => docType(d) === 'fpm' || docType(d) === 'eu');
  const pressmDocs = fullTextDocs.filter(d => docType(d) === 'pressm');
  const extDocs    = fullTextDocs.filter(d => docType(d) === 'ext');
  const skrDocs    = fullTextDocs.filter(d => docType(d) === 'skr');
 
  // Upgrade government SWOT entries where we now have full text
  refined.stakeholderSwot = refined.stakeholderSwot.map(sh => {
    if (sh.role === 'government') {
      const enrichedStrengths: AnalysisSwotEntry[] = [
        ...propDocs.slice(0, 3).map(d => buildEnrichedEntry(d, topic, lang, passageMax)),
        ...sfsDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, passageMax)),
        ...skrDocs.slice(0, 1).map(d => buildEnrichedEntry(d, topic, lang, passageMax)),
        ...pressmDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, passageMax)),
      ];
      const enrichedWeaknesses: AnalysisSwotEntry[] = betDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, passageMax));
      const enrichedOpportunities: AnalysisSwotEntry[] = [
        ...euDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, passageMax)),
        ...skrDocs.slice(1, 2).map(d => buildEnrichedEntry(d, topic, lang, passageMax)),
      ];
      const enrichedThreats: AnalysisSwotEntry[] = motDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, passageMax));
 
      // Merge: prefer enriched entries, fall back to initial placeholders
      return {
        ...sh,
        swot: {
          strengths:     enrichedStrengths.length > 0 ? enrichedStrengths : sh.swot.strengths,
          weaknesses:    enrichedWeaknesses.length > 0 ? enrichedWeaknesses : sh.swot.weaknesses,
          opportunities: enrichedOpportunities.length > 0 ? enrichedOpportunities : sh.swot.opportunities,
          threats:       enrichedThreats.length > 0 ? enrichedThreats : sh.swot.threats,
        },
      };
    }
    if (sh.role === 'parliament') {
      const enrichedStrengths: AnalysisSwotEntry[] = [
        ...betDocs.slice(0, 3).map(d => buildEnrichedEntry(d, topic, lang, passageMax)),
        ...motDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, passageMax)),
      ];
      const enrichedThreats: AnalysisSwotEntry[] = propDocs.slice(0, 1).map(d => buildEnrichedEntry(d, topic, lang, passageMax));
      return {
        ...sh,
        swot: {
          ...sh.swot,
          strengths: enrichedStrengths.length > 0 ? enrichedStrengths : sh.swot.strengths,
          threats:   enrichedThreats.length > 0 ? enrichedThreats : sh.swot.threats,
        },
      };
    }
    if (sh.role === 'private-sector') {
      const enrichedStrengths: AnalysisSwotEntry[] = [
        ...sfsDocs.slice(0, 1).map(d => buildEnrichedEntry(d, topic, lang, passageMax)),
        ...extDocs.slice(0, 2).map(d => buildEnrichedEntry(d, topic, lang, passageMax)),
      ];
      const enrichedOpportunities: AnalysisSwotEntry[] = euDocs.slice(0, 1).map(d => buildEnrichedEntry(d, topic, lang, passageMax));
      return {
        ...sh,
        swot: {
          ...sh.swot,
          strengths:     enrichedStrengths.length > 0 ? enrichedStrengths : sh.swot.strengths,
          opportunities: enrichedOpportunities.length > 0 ? enrichedOpportunities : sh.swot.opportunities,
        },
      };
    }
    return sh;
  });
 
  // Rebuild watch points with enriched context
  refined.watchPoints = buildWatchPoints(docs, topic, lang);
 
  // Recalculate confidence score with enriched data
  refined.confidenceScore = calculateConfidenceScore(docs);
  refined.enrichedCount = metadataCount;
 
  // Refresh policy assessment narrative with enriched evidence
  refined.policyAssessment = buildPolicyAssessment(docs, topic, lang);
 
  // Collect narrative frames from full-text docs and (optionally) add a mindmap branch
  const allFrames = new Set<string>();
  fullTextDocs.slice(0, 20).forEach(d => detectNarrativeFrames(d).forEach(f => allFrames.add(f)));
 
  // Enrich mindmap with additional data from full text analysis
  refined.mindmapBranches = buildMindmapBranches(docs, topic, refined.policyAssessment.domains, lang);
 
  // Add civil society branch if we have external docs
  const civilSocietyDocs = fullTextDocs.filter(d => ['ext', 'fpm', 'eu'].includes(docType(d)));
  if (civilSocietyDocs.length > 0 && allFrames.size > 0) {
    // Add a narrative analysis branch to mindmap
    const hasBranch = refined.mindmapBranches.some(b => b.label === narrativeFramesLabel(lang));
    if (!hasBranch) {
      refined.mindmapBranches.push({
        label: narrativeFramesLabel(lang),
        color: 'orange',
        icon: '๐ŸŽฏ',
        items: [...allFrames].slice(0, 6),
      });
    }
  }
 
  return refined;
}
 
// ---------------------------------------------------------------------------
// Iteration 3: validateCompleteness
// ---------------------------------------------------------------------------
 
async function validateCompleteness(
  analysis: AnalysisResult,
  docs: RawDocument[],
): Promise<ValidationResult> {
  const issues: string[] = [];
  const suggestions: string[] = [];
  let score = 100;
 
  // Check stakeholder coverage
  for (const sh of analysis.stakeholderSwot) {
    const { strengths, weaknesses, opportunities, threats } = sh.swot;
    if (strengths.length === 0) {
      issues.push(`${sh.name}: no strengths entries`);
      score -= 5;
    }
    if (weaknesses.length === 0) {
      suggestions.push(`${sh.name}: consider adding weakness analysis`);
      score -= 2;
    }
    if (opportunities.length === 0) {
      suggestions.push(`${sh.name}: consider adding opportunity analysis`);
      score -= 2;
    }
    if (threats.length === 0) {
      suggestions.push(`${sh.name}: consider adding threat analysis`);
      score -= 2;
    }
    // Check for placeholder-only entries (no document evidence backing them)
    const allEntries = [...strengths, ...weaknesses, ...opportunities, ...threats];
    const allPlaceholders = allEntries.length > 0 && allEntries.every(e => e.sourceDocIds.length === 0);
    if (allPlaceholders) {
      issues.push(`${sh.name}: all SWOT entries lack document evidence (sourceDocIds empty) โ€” enrich with document content`);
      score -= 10;
    }
  }
 
  // Check policy domain detection
  if (analysis.policyAssessment.domains.length === 0) {
    issues.push('No policy domains detected โ€” document titles may need more descriptive text');
    score -= 5;
  }
 
  // Check watch points
  if (analysis.watchPoints.length === 0) {
    suggestions.push('No watch points generated โ€” check for actionable document types (prop, bet, sfs)');
    score -= 3;
  }
 
  // Check enrichment ratio โ€” differentiate metadata-enriched vs full-text
  const fullTextAvailable = docs.filter(hasFullTextContent).length;
  if (analysis.documentCount > 0 && analysis.enrichedCount === 0) {
    issues.push('No documents have been enriched โ€” analysis quality is limited to raw metadata');
    score -= 15;
  } else if (analysis.enrichedCount > 0 && fullTextAvailable === 0) {
    suggestions.push('Documents are metadata-enriched but lack full text โ€” consider using include_full_text=true for deeper analysis');
    score -= 5;
  }
 
  // Check confidence score
  if (analysis.confidenceScore < 30) {
    issues.push(`Low confidence score (${analysis.confidenceScore}/100) โ€” fetch more documents or enrich with full text`);
    score -= 5;
  }
 
  // Bonus: rich analysis with many enriched documents
  if (analysis.enrichedCount >= 3) {
    score = Math.min(100, score + 5);
  }
  // Extra bonus for full-text enrichment
  if (fullTextAvailable >= 2) {
    score = Math.min(100, score + 3);
  }
 
  const finalScore = Math.max(0, score);
  return {
    passed: finalScore >= 60,
    score: finalScore,
    issues,
    suggestions,
  };
}
 
// ---------------------------------------------------------------------------
// Exported pipeline singleton
// ---------------------------------------------------------------------------
 
/**
 * The default AI analysis pipeline implementation.
 *
 * Usage in generators:
 * ```ts
 * import { aiAnalysisPipeline } from '../ai-analysis/pipeline.js';
 * const result = await aiAnalysisPipeline.analyzeDocuments(docs, { depth, lang, focusTopic });
 * if (depth !== 'quick') {
 *   const refined = await aiAnalysisPipeline.refineAnalysis(result, docs, { depth, lang, focusTopic });
 *   if (depth === 'deep') {
 *     await aiAnalysisPipeline.validateCompleteness(refined, docs);
 *   }
 * }
 * ```
 */
export const aiAnalysisPipeline: AnalysisPipeline = {
  analyzeDocuments,
  refineAnalysis,
  validateCompleteness,
};
 
/**
 * Run the full analysis pipeline according to the specified depth.
 * Returns the final AnalysisResult, optional ValidationResult, and
 * per-iteration timing data for audit metadata.
 *
 * @param docs - Raw documents to analyse
 * @param options - Pipeline options (depth, lang, focusTopic)
 * @returns `{ analysis, validation, iterationDurationsMs }` where
 *   validation is null for depth < 'deep' and iterationDurationsMs
 *   contains one entry per completed iteration/validation pass.
 */
export async function runAnalysisPipeline(
  docs: RawDocument[],
  options: AnalysisPipelineOptions,
): Promise<{ analysis: AnalysisResult; validation: ValidationResult | null; iterationDurationsMs: number[] }> {
  const iterationDurationsMs: number[] = [];
 
  // Iteration 1
  const t1 = Date.now();
  let analysis = await aiAnalysisPipeline.analyzeDocuments(docs, options);
  iterationDurationsMs.push(Date.now() - t1);
 
  // Iteration 2 (standard + deep)
  if (options.depth !== 'quick') {
    const t2 = Date.now();
    analysis = await aiAnalysisPipeline.refineAnalysis(analysis, docs, options);
    iterationDurationsMs.push(Date.now() - t2);
  }
 
  // Iteration 3 โ€” validation (deep only)
  let validation: ValidationResult | null = null;
  if (options.depth === 'deep') {
    const t3 = Date.now();
    validation = await aiAnalysisPipeline.validateCompleteness(analysis, docs);
    iterationDurationsMs.push(Date.now() - t3);
    // Bump iterationsCompleted to reflect the validation pass
    analysis = { ...analysis, iterationsCompleted: 3, completedAt: new Date().toISOString() };
  }
 
  return { analysis, validation, iterationDurationsMs };
}