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 | 28x 28x 28x 28x 28x 28x 124x 65x 65x 65x 59x 59x 1711x 65x 1664x 85x 71x 71x 37x 37x 29x 1x 1x 3x 1x 1x 1x 71x 71x 71x 71x 71x 71x 71x 71x 16x 71x 1x 71x 71x 1x 71x 55x 71x 71x 3x 71x 69x 71x 71x 1x 71x 70x 71x 71x 1x 71x 70x 71x 71x 71x 71x 71x 3x 71x 1x 71x 68x 71x 71x 71x 71x 14x 71x 57x 71x 71x 71x 71x 71x 1x 71x 70x 71x 1x 71x 71x 71x 71x 71x 71x 71x 71x 1x 71x 70x 71x 71x 1x 71x 71x 71x 71x 71x 71x 71x 2x 71x 69x 71x 71x 71x 71x 1x 71x 70x 71x 71x 71x 71x 71x 1x 71x 70x 71x 71x 71x 14x 71x 2x 71x 56x 71x 71x 71x 71x 14x 71x 1x 71x 71x 2x 71x 28x 28x 28x 28x 28x 28x 28x 28x 426x 426x 426x 426x 426x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 426x 426x 426x 426x 426x 426x 426x 426x 34x 426x | /**
* @module data-transformers/content-generators/ai-swot-analyzer
* @description Heuristic multi-perspective SWOT analysis builder.
*
* Produces substantive analytical SWOT entries for 6 stakeholder perspectives
* using document-type-aware routing and rules-based reasoning over parliamentary
* document metadata, summaries, and topics. Each entry carries justification,
* trend direction, confidence scoring, and optional quantitative evidence —
* rather than raw document title truncation.
*
* Note: the current implementation is deterministic and rules-based. It does
* NOT invoke LLM or MCP prompts; "AI" in the public API names is aspirational
* and kept for interface stability. A future iteration may wire the prompts
* into the editorial-framework MCP pipeline.
*
* Analytical prose (entry text, justification) is English-only even though the
* deep-inspection pipeline renders articles in all 14 language versions.
* Stakeholder names, roles, and context metadata labels ("Confidence",
* "Cross-references") are fully localised in all 14 supported languages.
*
* The six perspectives are:
* 1. Government Coalition (M, KD, L + SD support)
* 2. Social Democratic Opposition (S, V, C, MP)
* 3. EU / International Actors
* 4. Private Sector & Business
* 5. Civil Society & NGOs
* 6. Swedish Citizens / Voters
*
* @author Hack23 AB
* @license Apache-2.0
*/
import type { Language } from '../../types/language.js';
import type { SwotImpact, TrendDirection } from '../../types/article.js';
import type { StakeholderSwot } from './stakeholder-swot-section.js';
import type { RawDocument } from '../types.js';
// TrendDirection is canonically defined in types/article.ts — import from there directly
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/** One of the six recognised stakeholder perspectives */
export type StakeholderPerspective =
| 'government-coalition'
| 'opposition'
| 'eu-international'
| 'private-sector'
| 'civil-society'
| 'citizens-voters';
/**
* Enhanced SWOT entry with AI-generated analytical content.
* Extends the base `SwotEntry` shape with additional intelligence fields.
*/
export interface AISwotEntry {
/** Short analytical statement (the main SWOT item) */
text: string;
/** Relative policy impact or significance */
impact: SwotImpact;
/** Reasoning explaining why this item was included */
justification: string;
/** IDs or titles of related documents that support this entry */
relatedDocuments: string[];
/** Whether this factor is getting better, static, or worse */
trendDirection: TrendDirection;
/** Optional metric supporting the entry (e.g. "73% majority", "SEK 2.1 bn") */
quantitativeEvidence?: string;
}
/** A link connecting a SWOT entry in one stakeholder analysis to another */
export interface SwotCrossReference {
fromStakeholder: StakeholderPerspective;
fromQuadrant: 'strengths' | 'weaknesses' | 'opportunities' | 'threats';
toStakeholder: StakeholderPerspective;
toQuadrant: 'strengths' | 'weaknesses' | 'opportunities' | 'threats';
rationale: string;
}
/** Full AI SWOT analysis for a single stakeholder */
export interface AISwotAnalysis {
stakeholder: string;
perspective: StakeholderPerspective;
strengths: AISwotEntry[];
weaknesses: AISwotEntry[];
opportunities: AISwotEntry[];
threats: AISwotEntry[];
crossReferences: SwotCrossReference[];
/** Overall analytical confidence (0–1) */
confidenceScore: number;
}
// ---------------------------------------------------------------------------
// Localised stakeholder names (all 14 languages)
// ---------------------------------------------------------------------------
export const STAKEHOLDER_NAMES: Readonly<Record<StakeholderPerspective, Readonly<Record<Language, string>>>> = {
'government-coalition': {
en: 'Government Coalition',
sv: 'Regeringskoalitionen',
da: 'Regeringskoalitionen',
no: 'Regjeringskoalisjonen',
fi: 'Hallituskoalitio',
de: 'Regierungskoalition',
fr: 'Coalition gouvernementale',
es: 'Coalición gubernamental',
nl: 'Regeringscoalitie',
ar: 'الائتلاف الحكومي',
he: 'הקואליציה הממשלתית',
ja: '政府連立',
ko: '정부 연립',
zh: '执政联盟',
},
opposition: {
en: 'Social Democratic Opposition',
sv: 'Socialdemokratisk opposition',
da: 'Socialdemokratisk opposition',
no: 'Sosialdemokratisk opposisjon',
fi: 'Sosiaalidemokraattinen oppositio',
de: 'Sozialdemokratische Opposition',
fr: 'Opposition sociale-démocrate',
es: 'Oposición socialdemócrata',
nl: 'Sociaaldemocratische oppositie',
ar: 'المعارضة الاشتراكية الديمقراطية',
he: 'האופוזיציה הסוציאל-דמוקרטית',
ja: '社会民主主義野党',
ko: '사회민주주의 야당',
zh: '社会民主主义反对派',
},
'eu-international': {
en: 'EU & International Actors',
sv: 'EU och internationella aktörer',
da: 'EU og internationale aktører',
no: 'EU og internasjonale aktører',
fi: 'EU ja kansainväliset toimijat',
de: 'EU & Internationale Akteure',
fr: 'UE et acteurs internationaux',
es: 'UE y actores internacionales',
nl: 'EU & Internationale actoren',
ar: 'الاتحاد الأوروبي والجهات الدولية',
he: 'האיחוד האירופי וגורמים בינלאומיים',
ja: 'EUと国際的アクター',
ko: 'EU 및 국제 행위자',
zh: '欧盟与国际行为者',
},
'private-sector': {
en: 'Private Sector & Business',
sv: 'Privat sektor och näringsliv',
da: 'Privat sektor og erhvervsliv',
no: 'Privat sektor og næringsliv',
fi: 'Yksityissektori ja elinkeinoelämä',
de: 'Privatwirtschaft & Unternehmen',
fr: 'Secteur privé & entreprises',
es: 'Sector privado y empresas',
nl: 'Private sector & bedrijfsleven',
ar: 'القطاع الخاص والأعمال',
he: 'המגזר הפרטי והעסקים',
ja: '民間セクターとビジネス',
ko: '민간 부문 및 기업',
zh: '私营部门与商业',
},
'civil-society': {
en: 'Civil Society & NGOs',
sv: 'Civilsamhälle och NGO:er',
da: 'Civilsamfund og NGO\'er',
no: 'Sivilsamfunn og frivillige organisasjoner',
fi: 'Kansalaisyhteiskunta ja kansalaisjärjestöt',
de: 'Zivilgesellschaft & NGOs',
fr: 'Société civile & ONG',
es: 'Sociedad civil y ONG',
nl: 'Maatschappelijk middenveld & NGO\'s',
ar: 'المجتمع المدني ومنظمات غير حكومية',
he: 'החברה האזרחית וארגוני מלכ"ר',
ja: '市民社会とNGO',
ko: '시민 사회 및 NGO',
zh: '公民社会与非政府组织',
},
'citizens-voters': {
en: 'Swedish Citizens & Voters',
sv: 'Svenska medborgare och väljare',
da: 'Svenske borgere og vælgere',
no: 'Svenske borgere og velgere',
fi: 'Ruotsalaiset kansalaiset ja äänestäjät',
de: 'Schwedische Bürger & Wähler',
fr: 'Citoyens & électeurs suédois',
es: 'Ciudadanos y votantes suecos',
nl: 'Zweedse burgers & kiezers',
ar: 'المواطنون والناخبون السويديون',
he: 'אזרחים ובוחרים שבדים',
ja: 'スウェーデン市民と有権者',
ko: '스웨덴 시민 및 유권자',
zh: '瑞典公民与选民',
},
};
// ---------------------------------------------------------------------------
// Localised stakeholder roles (all 14 languages)
// ---------------------------------------------------------------------------
const STAKEHOLDER_ROLES: Readonly<Record<StakeholderPerspective, Readonly<Record<Language, string>>>> = {
'government-coalition': {
en: 'Tidö Agreement parties: M, KD, L with SD support',
sv: 'Tidöavtalspartierna: M, KD, L med SD:s stöd',
da: 'Tidö-aftalepartierne: M, KD, L med SD-støtte',
no: 'Tidö-avtalepartiene: M, KD, L med SD-støtte',
fi: 'Tidö-sopimuspuolueet: M, KD, L SD:n tuella',
de: 'Tidö-Vereinbarungsparteien: M, KD, L mit SD-Unterstützung',
fr: 'Partis de l\'accord Tidö: M, KD, L avec soutien SD',
es: 'Partidos del acuerdo Tidö: M, KD, L con apoyo SD',
nl: 'Tidö-akkoordpartijen: M, KD, L met SD-steun',
ar: 'أحزاب اتفاقية تيدو: M وKD وL بدعم SD',
he: 'מפלגות הסכם טידו: M, KD, L בתמיכת SD',
ja: 'ティドー協定政党: M、KD、L(SD支持)',
ko: '티도 협정 정당: M, KD, L (SD 지원)',
zh: 'Tidö协议党派:M、KD、L,获SD支持',
},
opposition: {
en: 'S, V, C, MP — alternative governance bloc',
sv: 'S, V, C, MP — alternativt styrningsblock',
da: 'S, V, C, MP — alternativ styringsblok',
no: 'S, V, C, MP — alternativ styringsblokk',
fi: 'S, V, C, MP — vaihtoehtoinen hallintoryhmä',
de: 'S, V, C, MP — alternatives Regierungsblock',
fr: 'S, V, C, MP — bloc de gouvernance alternatif',
es: 'S, V, C, MP — bloque de gobierno alternativo',
nl: 'S, V, C, MP — alternatief regeringsblok',
ar: 'S وV وC وMP — كتلة حوكمة بديلة',
he: 'S, V, C, MP — גוש שלטון חלופי',
ja: 'S、V、C、MP — 代替統治ブロック',
ko: 'S, V, C, MP — 대안 통치 블록',
zh: 'S、V、C、MP — 替代执政集团',
},
'eu-international': {
en: 'European Union institutions, international bodies & diplomatic actors',
sv: 'EU:s institutioner, internationella organ och diplomatiska aktörer',
da: 'EU-institutioner, internationale organer og diplomatiske aktører',
no: 'EU-institusjoner, internasjonale organer og diplomatiske aktører',
fi: 'EU-instituutiot, kansainväliset elimet ja diplomaattiset toimijat',
de: 'EU-Institutionen, internationale Gremien & diplomatische Akteure',
fr: 'Institutions européennes, organismes internationaux & acteurs diplomatiques',
es: 'Instituciones europeas, organismos internacionales y actores diplomáticos',
nl: 'EU-instellingen, internationale organen & diplomatieke actoren',
ar: 'المؤسسات الأوروبية والهيئات الدولية والجهات الدبلوماسية',
he: 'מוסדות האיחוד האירופי, גופים בינלאומיים ושחקנים דיפלומטיים',
ja: 'EU機関・国際機関・外交的行為者',
ko: 'EU 기관, 국제 기구 및 외교적 행위자',
zh: '欧盟机构、国际组织与外交行为者',
},
'private-sector': {
en: 'Companies, industry federations, employers & investors',
sv: 'Företag, branschorganisationer, arbetsgivare och investerare',
da: 'Virksomheder, brancheforeninger, arbejdsgivere og investorer',
no: 'Bedrifter, bransjeforeninger, arbeidsgivere og investorer',
fi: 'Yritykset, toimialajärjestöt, työnantajat ja sijoittajat',
de: 'Unternehmen, Branchenverbände, Arbeitgeber & Investoren',
fr: 'Entreprises, fédérations sectorielles, employeurs & investisseurs',
es: 'Empresas, federaciones sectoriales, empleadores e inversores',
nl: 'Bedrijven, brancheverenigingen, werkgevers & investeerders',
ar: 'الشركات والاتحادات القطاعية وأصحاب العمل والمستثمرون',
he: 'חברות, התאחדויות ענפיות, מעסיקים ומשקיעים',
ja: '企業・業界団体・雇用主・投資家',
ko: '기업, 업계 연합, 고용주 및 투자자',
zh: '企业、行业协会、雇主与投资者',
},
'civil-society': {
en: 'Trade unions, advocacy groups, human rights organisations & media',
sv: 'Fackföreningar, påtryckargrupper, människorättsorganisationer och media',
da: 'Fagforeninger, interesseorganisationer, menneskerettighedsorganisationer og medier',
no: 'Fagforeninger, interesseorganisasjoner, menneskerettighetsorganisasjoner og medier',
fi: 'Ammattiliitot, edunvalvontaryhmät, ihmisoikeusjärjestöt ja media',
de: 'Gewerkschaften, Interessengruppen, Menschenrechtsorganisationen & Medien',
fr: 'Syndicats, groupes de plaidoyer, organisations de droits humains & médias',
es: 'Sindicatos, grupos de defensa, organizaciones de derechos humanos y medios',
nl: 'Vakbonden, belangengroepen, mensenrechtenorganisaties & media',
ar: 'النقابات ومجموعات المناصرة ومنظمات حقوق الإنسان والإعلام',
he: 'ועדי עובדים, קבוצות הסברה, ארגוני זכויות אדם ותקשורת',
ja: '労働組合・権利擁護団体・人権団体・メディア',
ko: '노동조합, 권익 단체, 인권 단체 및 미디어',
zh: '工会、倡导团体、人权组织与媒体',
},
'citizens-voters': {
en: 'Electorate, public service users & democratic stakeholders',
sv: 'Valmanskåren, användare av offentliga tjänster och demokratiska intressenter',
da: 'Valgberettigede, brugere af offentlige tjenester og demokratiske interessenter',
no: 'Stemmeberettigede, brukere av offentlige tjenester og demokratiske interessenter',
fi: 'Äänioikeutetut, julkisten palvelujen käyttäjät ja demokraattiset sidosryhmät',
de: 'Wählerschaft, Nutzer öffentlicher Dienste & demokratische Stakeholder',
fr: 'Électorat, usagers des services publics & parties prenantes démocratiques',
es: 'Electorado, usuarios de servicios públicos y partes interesadas democráticas',
nl: 'Kiezers, gebruikers van overheidsdiensten & democratische stakeholders',
ar: 'الناخبون ومستخدمو الخدمات العامة وأصحاب المصلحة الديمقراطية',
he: 'מצביעים, משתמשי שירותים ציבוריים ובעלי עניין דמוקרטיים',
ja: '有権者・公共サービス利用者・民主的利害関係者',
ko: '유권자, 공공 서비스 이용자 및 민주적 이해 관계자',
zh: '选民、公共服务用户与民主利益相关者',
},
};
// ---------------------------------------------------------------------------
// Localised context metadata labels (all 14 languages)
// ---------------------------------------------------------------------------
const CONTEXT_LABELS: Readonly<{
confidence: Readonly<Record<Language, string>>;
crossReferences: Readonly<Record<Language, string>>;
}> = {
confidence: {
en: 'Confidence',
sv: 'Konfidens',
da: 'Tillid',
no: 'Tillit',
fi: 'Luottamus',
de: 'Konfidenz',
fr: 'Confiance',
es: 'Confianza',
nl: 'Vertrouwen',
ar: 'الثقة',
he: 'ביטחון',
ja: '信頼度',
ko: '신뢰도',
zh: '置信度',
},
crossReferences: {
en: 'Cross-references',
sv: 'Korsreferenser',
da: 'Krydsreferencer',
no: 'Kryssreferanser',
fi: 'Ristiviittaukset',
de: 'Querverweise',
fr: 'Références croisées',
es: 'Referencias cruzadas',
nl: 'Kruisverwijzingen',
ar: 'مراجع متقاطعة',
he: 'הפניות צולבות',
ja: '相互参照',
ko: '교차 참조',
zh: '交叉引用',
},
};
// ---------------------------------------------------------------------------
// Document classification helpers
// ---------------------------------------------------------------------------
/** Minimum summary length to prefer summary over title */
const MIN_SUMMARY_LENGTH = 20;
/** Maximum characters to use from a summary */
const MAX_SUMMARY_CHARS = 120;
/** Maximum characters to use from a document title */
const MAX_TITLE_CHARS = 100;
function titleOf(d: RawDocument): string {
return (d.titel || d.title || d.rubrik || d.dokumentnamn || d.dok_id || '').trim();
}
function summaryOf(d: RawDocument): string {
return (d.summary || d.notis || d.undertitel || '').trim();
}
/** Extract meaningful content for an AI entry — prefer summary over raw title */
function contentOf(d: RawDocument, fallback: string): string {
const s = summaryOf(d);
if (s.length > MIN_SUMMARY_LENGTH) return s.slice(0, MAX_SUMMARY_CHARS);
const t = titleOf(d);
return t.length > 0 ? t.slice(0, MAX_TITLE_CHARS) : fallback;
}
function makeAIEntry(
text: string,
impact: SwotImpact,
justification: string,
relatedDocuments: string[],
trendDirection: TrendDirection,
quantitativeEvidence?: string,
): AISwotEntry {
return { text, impact, justification, relatedDocuments, trendDirection, quantitativeEvidence };
}
function docEntry(
d: RawDocument,
defaultText: string,
impact: SwotImpact,
justification: string,
trendDirection: TrendDirection,
quantEvidence?: string,
): AISwotEntry {
return makeAIEntry(
contentOf(d, defaultText),
impact,
justification,
[titleOf(d) || d.dok_id || ''].filter(Boolean),
trendDirection,
quantEvidence,
);
}
// ---------------------------------------------------------------------------
// Topic-aware analytical statement builder
// ---------------------------------------------------------------------------
/** Build a topical statement: "X in {topic}" or strip %t placeholder when absent */
function withTopic(template: string, topic: string | null): string {
if (!topic) return template.replaceAll('%t', '');
return template.replaceAll('%t', topic);
}
// ---------------------------------------------------------------------------
// Pre-bucketed document classification (single pass)
// ---------------------------------------------------------------------------
/** Pre-classified document buckets to avoid repeated filtering in each builder */
interface DocBuckets {
prop: RawDocument[];
skr: RawDocument[];
sfs: RawDocument[];
pressm: RawDocument[];
bet: RawDocument[];
fpm: RawDocument[];
mot: RawDocument[];
ext: RawDocument[];
other: RawDocument[];
}
/** Classify docs into type buckets in a single pass */
function bucketDocs(docs: RawDocument[]): DocBuckets {
const b: DocBuckets = { prop: [], skr: [], sfs: [], pressm: [], bet: [], fpm: [], mot: [], ext: [], other: [] };
for (const d of docs) {
const t = d.doktyp || d.documentType || '';
switch (t) {
case 'prop': b.prop.push(d); break;
case 'skr': b.skr.push(d); break;
case 'sfs': b.sfs.push(d); break;
case 'pressm': b.pressm.push(d); break;
case 'bet': b.bet.push(d); break;
case 'fpm': b.fpm.push(d); break;
case 'mot': b.mot.push(d); break;
case 'ext': b.ext.push(d); break;
default:
// SFS-by-name heuristic (doktyp missing but dokumentnamn starts with SFS)
if ((d.dokumentnamn || '').startsWith('SFS')) { b.sfs.push(d); }
else { b.other.push(d); }
break;
}
}
return b;
}
/** Sum of all bucketed documents */
function bucketTotal(b: DocBuckets): number {
return b.prop.length + b.skr.length + b.sfs.length + b.pressm.length
+ b.bet.length + b.fpm.length + b.mot.length + b.ext.length
+ b.other.length;
}
// ---------------------------------------------------------------------------
// Per-stakeholder SWOT builders
// ---------------------------------------------------------------------------
function buildGovernmentSwot(
b: DocBuckets,
topic: string | null,
_lang: Language,
): Pick<AISwotAnalysis, 'strengths' | 'weaknesses' | 'opportunities' | 'threats'> {
const { prop: propDocs, skr: skrDocs, sfs: sfsDocs, pressm: pressmDocs, bet: betDocs, fpm: euDocs, mot: motDocs } = b;
const topicStr = topic ? ` on ${topic}` : '';
const total = bucketTotal(b);
const docCount = `${total} parliamentary document${total !== 1 ? 's' : ''} examined`;
const strengths: AISwotEntry[] = [];
propDocs.slice(0, 2).forEach(d => {
strengths.push(docEntry(
d, withTopic('Government proposition%t', topicStr ? ` ${topic}` : null),
'high',
`Government-initiated proposition demonstrates legislative agenda-setting capacity${topicStr}`,
'stable',
));
});
sfsDocs.slice(0, 1).forEach(d => {
strengths.push(docEntry(
d, withTopic('Enacted law%t', topicStr ? ` ${topic}` : null),
'high',
`Enacted statute indicates completed legislative cycle${topicStr}`,
'stable',
));
});
pressmDocs.slice(0, 1).forEach(d => {
strengths.push(docEntry(
d, withTopic('Government communication%t', topicStr ? ` ${topic}` : null),
'medium',
`Press communication signals proactive policy messaging${topicStr}`,
'stable',
));
});
skrDocs.slice(0, 1).forEach(d => {
strengths.push(docEntry(
d, withTopic('Government written communication (skrivelse)%t', topicStr ? ` ${topic}` : null),
'medium',
`Government skrivelse conveys policy position or report to parliament${topicStr}`,
'stable',
));
});
if (strengths.length === 0) {
strengths.push(makeAIEntry(
withTopic('Policy initiative and agenda-setting%t', topicStr ? ` on ${topic}` : ''),
'medium',
`Government holds exclusive right to introduce primary legislation${topicStr}`,
[],
'stable',
));
}
const weaknesses: AISwotEntry[] = [];
betDocs.slice(0, 2).forEach(d => {
weaknesses.push(docEntry(
d, 'Implementation scrutiny in committee report',
'medium',
`Committee scrutiny reveals implementation challenges${topicStr}`,
'stable',
));
});
if (weaknesses.length === 0) {
weaknesses.push(makeAIEntry(
withTopic('Implementation timeline and resource prioritisation%t', topicStr ? ` for ${topic}` : ''),
'medium',
`Complex legislation requires sustained administrative capacity${topicStr}`,
[],
'stable',
));
}
const opportunities: AISwotEntry[] = [];
euDocs.slice(0, 2).forEach(d => {
opportunities.push(docEntry(
d, 'EU framework position paper',
'high',
`EU/international alignment can strengthen domestic policy credibility${topicStr}`,
'improving',
));
});
if (opportunities.length === 0) {
opportunities.push(makeAIEntry(
withTopic('EU and international cooperation%t', topicStr ? ` on ${topic}` : ''),
'high',
`Multilateral frameworks provide legitimacy and co-funding for domestic reforms${topicStr}`,
[],
'improving',
));
}
const threats: AISwotEntry[] = [];
motDocs.slice(0, 2).forEach(d => {
threats.push(docEntry(
d, 'Opposition motion challenging policy',
'medium',
`Opposition motions create parliamentary counter-pressure${topicStr}`,
'stable',
));
});
if (threats.length === 0) {
threats.push(makeAIEntry(
withTopic('Execution risks and political resistance%t', topicStr ? ` to ${topic} reform` : ''),
'medium',
`Policy implementation faces stakeholder friction and opposition challenge${topicStr}`,
[],
'stable',
docCount,
));
}
return { strengths, weaknesses, opportunities, threats };
}
function buildOppositionSwot(
b: DocBuckets,
topic: string | null,
_lang: Language,
): Pick<AISwotAnalysis, 'strengths' | 'weaknesses' | 'opportunities' | 'threats'> {
const { bet: betDocs, mot: motDocs, prop: propDocs } = b;
const topicStr = topic ? ` on ${topic}` : '';
const strengths: AISwotEntry[] = [];
betDocs.slice(0, 2).forEach(d => {
strengths.push(docEntry(
d, 'Committee oversight report',
'high',
`Committee report enables structured parliamentary scrutiny${topicStr}`,
'stable',
));
});
motDocs.slice(0, 2).forEach(d => {
strengths.push(docEntry(
d, 'Opposition motion for alternative policy',
'medium',
`Tabling motions demonstrates alternative policy capacity and public positioning${topicStr}`,
'stable',
));
});
if (strengths.length === 0) {
strengths.push(makeAIEntry(
withTopic('Parliamentary oversight and scrutiny%t', topicStr ? ` of ${topic} proposals` : ''),
'high',
`Opposition fulfils democratic accountability function${topicStr}`,
[],
'stable',
));
}
const weaknesses: AISwotEntry[] = [
makeAIEntry(
withTopic('Limited access to implementation data%t', topicStr ? ` on ${topic}` : ''),
'medium',
`Government controls executive information; opposition relies on public documents${topicStr}`,
[],
'stable',
),
];
const opportunities: AISwotEntry[] = [
makeAIEntry(
withTopic('Cross-party consensus building%t', topicStr ? ` on ${topic}` : ''),
'high',
`Issue salience creates openings for coalition with centrist defectors${topicStr}`,
[],
'improving',
),
];
const threats: AISwotEntry[] = [];
propDocs.slice(0, 1).forEach(d => {
threats.push(docEntry(
d, 'Government proposition limiting amendment scope',
'medium',
`Government majority can pass legislation with minimal opposition amendments${topicStr}`,
'stable',
));
});
if (threats.length === 0) {
threats.push(makeAIEntry(
withTopic('Government majority limiting amendment capacity%t', topicStr ? ` on ${topic}` : ''),
'medium',
`Parliamentary arithmetic constrains opposition legislative influence${topicStr}`,
[],
'stable',
));
}
return { strengths, weaknesses, opportunities, threats };
}
function buildEUInternationalSwot(
b: DocBuckets,
topic: string | null,
_lang: Language,
): Pick<AISwotAnalysis, 'strengths' | 'weaknesses' | 'opportunities' | 'threats'> {
const { fpm: euDocs, ext: extDocs } = b;
const topicStr = topic ? ` on ${topic}` : '';
const strengths: AISwotEntry[] = [];
euDocs.slice(0, 2).forEach(d => {
strengths.push(docEntry(
d, 'EU/international regulatory framework',
'high',
`EU regulatory alignment provides Sweden with binding legal framework and co-funding${topicStr}`,
'improving',
));
});
if (strengths.length === 0) {
strengths.push(makeAIEntry(
withTopic('EU regulatory frameworks and directives%t', topicStr ? ` for ${topic}` : ''),
'high',
`EU membership provides supranational standards that shape national policy${topicStr}`,
[],
'stable',
));
}
extDocs.slice(0, 1).forEach(d => {
strengths.push(docEntry(
d, 'External expert input',
'medium',
`International expertise validates and contextualises domestic policy positions${topicStr}`,
'stable',
));
});
const weaknesses: AISwotEntry[] = [
makeAIEntry(
withTopic('Implementation variation across EU member states%t', topicStr ? ` regarding ${topic}` : ''),
'medium',
`Divergent transposition timelines can create competitive disadvantages for Sweden${topicStr}`,
[],
'stable',
),
];
const opportunities: AISwotEntry[] = [
makeAIEntry(
withTopic('Diplomatic leadership and norm-setting%t', topicStr ? ` on ${topic}` : ''),
'high',
`Sweden can use international forums to shape standards and attract investment${topicStr}`,
[],
'improving',
),
];
const threats: AISwotEntry[] = [
makeAIEntry(
withTopic('Geopolitical uncertainty impacting Swedish policy space%t', topicStr ? ` for ${topic}` : ''),
'high',
`Shifting international dynamics can constrain or override domestic policy choices${topicStr}`,
[],
'deteriorating',
),
];
return { strengths, weaknesses, opportunities, threats };
}
function buildPrivateSectorSwot(
b: DocBuckets,
topic: string | null,
_lang: Language,
): Pick<AISwotAnalysis, 'strengths' | 'weaknesses' | 'opportunities' | 'threats'> {
const { sfs: sfsDocs, ext: extDocs } = b;
const topicStr = topic ? ` in ${topic}` : '';
const strengths: AISwotEntry[] = [];
extDocs.slice(0, 2).forEach(d => {
strengths.push(docEntry(
d, 'Industry input to policy process',
'high',
`Industry representation in consultation demonstrates established influence channels${topicStr}`,
'stable',
));
});
if (strengths.length === 0) {
strengths.push(makeAIEntry(
withTopic('Domain expertise and operational capacity%t', topicStr ? ` in ${topic}` : ''),
'high',
`Private sector holds implementation knowledge critical to policy success${topicStr}`,
[],
'stable',
));
}
const weaknesses: AISwotEntry[] = [
makeAIEntry(
withTopic('Compliance costs from new regulatory requirements%t', topicStr ? ` in ${topic}` : ''),
'medium',
`Legislative changes impose adaptation costs particularly on SMEs${topicStr}`,
[],
'deteriorating',
),
];
sfsDocs.slice(0, 1).forEach(d => {
weaknesses.push(docEntry(
d, 'New regulatory requirement',
'medium',
`Enacted statute creates compliance obligations for business${topicStr}`,
'stable',
));
});
const opportunities: AISwotEntry[] = [
makeAIEntry(
withTopic('Investment and innovation from policy-driven market development%t', topicStr ? ` in ${topic}` : ''),
'high',
`Government programmes create new markets and procurement opportunities${topicStr}`,
[],
'improving',
),
];
const threats: AISwotEntry[] = [
makeAIEntry(
withTopic('Regulatory uncertainty during policy transition%t', topicStr ? ` on ${topic}` : ''),
'high',
`Short implementation timelines and evolving rules hamper business planning${topicStr}`,
[],
'deteriorating',
),
];
return { strengths, weaknesses, opportunities, threats };
}
function buildCivilSocietySwot(
b: DocBuckets,
topic: string | null,
_lang: Language,
): Pick<AISwotAnalysis, 'strengths' | 'weaknesses' | 'opportunities' | 'threats'> {
const { bet: betDocs, mot: motDocs } = b;
const topicStr = topic ? ` on ${topic}` : '';
const strengths: AISwotEntry[] = [];
betDocs.slice(0, 1).forEach(d => {
strengths.push(docEntry(
d, 'Civil society input in committee process',
'high',
`Committee consultation includes civil society perspectives that shape final legislation${topicStr}`,
'stable',
));
});
if (strengths.length === 0) {
strengths.push(makeAIEntry(
withTopic('Democratic accountability and rights advocacy%t', topicStr ? ` regarding ${topic}` : ''),
'high',
`Civil society provides independent oversight and public interest representation${topicStr}`,
[],
'stable',
));
}
const weaknesses: AISwotEntry[] = [
makeAIEntry(
withTopic('Resource constraints limiting monitoring capacity%t', topicStr ? ` for ${topic}` : ''),
'medium',
`NGOs often lack funding to mount sustained campaigns on complex legislation${topicStr}`,
[],
'stable',
),
];
const opportunities: AISwotEntry[] = [
makeAIEntry(
withTopic('Public mobilisation on rights-sensitive policies%t', topicStr ? ` related to ${topic}` : ''),
'high',
`Heightened media attention creates window for civil society agenda-setting${topicStr}`,
[],
'improving',
),
];
const threats: AISwotEntry[] = [];
motDocs.slice(0, 1).forEach(d => {
threats.push(docEntry(
d, 'Restrictive legislative motion',
'medium',
`Proposed legislation may restrict civic space or NGO operational freedoms${topicStr}`,
'deteriorating',
));
});
if (threats.length === 0) {
threats.push(makeAIEntry(
withTopic('Legislative changes reducing civic freedoms%t', topicStr ? ` in ${topic}` : ''),
'medium',
`Policy reforms can inadvertently curtail associational rights or protest space${topicStr}`,
[],
'stable',
));
}
return { strengths, weaknesses, opportunities, threats };
}
function buildCitizensSwot(
b: DocBuckets,
topic: string | null,
_lang: Language,
): Pick<AISwotAnalysis, 'strengths' | 'weaknesses' | 'opportunities' | 'threats'> {
const { prop: propDocs, sfs: sfsDocs, bet: betDocs } = b;
const topicStr = topic ? ` on ${topic}` : '';
const strengths: AISwotEntry[] = [];
sfsDocs.slice(0, 1).forEach(d => {
strengths.push(docEntry(
d, 'Enacted welfare or service law',
'high',
`Enacted legislation directly improves public service delivery${topicStr}`,
'stable',
));
});
if (strengths.length === 0) {
strengths.push(makeAIEntry(
withTopic('Democratic representation through elected parliament%t', topicStr ? ` on ${topic}` : ''),
'high',
`Citizens exercise electoral accountability over policy direction${topicStr}`,
[],
'stable',
));
}
const weaknesses: AISwotEntry[] = [
makeAIEntry(
withTopic('Information asymmetry on policy impacts%t', topicStr ? ` of ${topic}` : ''),
'medium',
`Complex legislation is difficult for citizens to evaluate without expert analysis${topicStr}`,
[],
'stable',
),
];
const opportunities: AISwotEntry[] = [];
propDocs.slice(0, 1).forEach(d => {
opportunities.push(docEntry(
d, 'Government reform proposition',
'high',
`Government reform proposals create opportunities for improved public services${topicStr}`,
'improving',
));
});
betDocs.slice(0, 1).forEach(d => {
opportunities.push(docEntry(
d, 'Transparent committee review process',
'medium',
`Open committee proceedings allow citizens to track legislative development${topicStr}`,
'stable',
));
});
if (opportunities.length === 0) {
opportunities.push(makeAIEntry(
withTopic('Policy reforms improving public service quality%t', topicStr ? ` for ${topic}` : ''),
'high',
`Parliamentary activity on this issue indicates political will to improve outcomes${topicStr}`,
[],
'improving',
));
}
const threats: AISwotEntry[] = [
makeAIEntry(
withTopic('Policy implementation gaps reducing service quality%t', topicStr ? ` in ${topic}` : ''),
'medium',
`Distance between legislative intent and administrative execution affects citizen outcomes${topicStr}`,
[],
'stable',
),
];
return { strengths, weaknesses, opportunities, threats };
}
// ---------------------------------------------------------------------------
// Cross-reference generator
// ---------------------------------------------------------------------------
function buildCrossReferences(b: DocBuckets, topic: string | null): SwotCrossReference[] {
const refs: SwotCrossReference[] = [];
// Government strengths → Opposition threats
if (b.prop.length > 0) {
refs.push({
fromStakeholder: 'government-coalition',
fromQuadrant: 'strengths',
toStakeholder: 'opposition',
toQuadrant: 'threats',
rationale: topic
? `Government propositions on ${topic} that reinforce coalition strengths simultaneously limit opposition influence`
: 'Government legislative agenda that strengthens coalition simultaneously constrains opposition amendment capacity',
});
}
// EU opportunities → Private sector opportunities
if (b.fpm.length > 0) {
refs.push({
fromStakeholder: 'eu-international',
fromQuadrant: 'opportunities',
toStakeholder: 'private-sector',
toQuadrant: 'opportunities',
rationale: topic
? `EU directives on ${topic} open cross-border market opportunities for Swedish business`
: 'EU regulatory harmonisation creates new market access opportunities for Swedish companies',
});
}
// Private sector regulatory burden → Civil society accountability (only when evidence present)
const hasRegulatoryDocs = b.sfs.length > 0 || b.skr.length > 0;
if (hasRegulatoryDocs) {
refs.push({
fromStakeholder: 'private-sector',
fromQuadrant: 'weaknesses',
toStakeholder: 'civil-society',
toQuadrant: 'opportunities',
rationale: topic
? `Business compliance challenges on ${topic} create space for civil society to advocate proportionate regulation`
: 'Regulatory compliance burdens provide civil society with advocacy leverage for balanced policy design',
});
}
return refs;
}
// ---------------------------------------------------------------------------
// Confidence score calculation
// ---------------------------------------------------------------------------
/** Baseline confidence with minimal document evidence */
const BASE_CONFIDENCE = 0.55;
/** Maximum bonus for document volume (capped at 10 extra documents) */
const MAX_DOC_VOLUME_BONUS = 0.20;
/** Confidence points added per document (capped by MAX_DOC_VOLUME_BONUS) */
const CONFIDENCE_PER_DOC = 0.02;
/** Maximum bonus for enriched full-text documents */
const MAX_ENRICHMENT_BONUS = 0.15;
/** Confidence points per enriched document (capped by MAX_ENRICHMENT_BONUS) */
const CONFIDENCE_PER_ENRICHED_DOC = 0.03;
/** Penalty when EU stakeholder has no fpm documents (low direct evidence) */
const EU_NO_DATA_PENALTY = -0.05;
/** Absolute maximum confidence (no analysis is 100% certain) */
const MAX_CONFIDENCE = 0.95;
/** Absolute minimum confidence (always some baseline reasoning possible) */
const MIN_CONFIDENCE = 0.40;
function computeConfidence(docs: RawDocument[], b: DocBuckets, perspective: StakeholderPerspective): number {
const docBonus = Math.min(MAX_DOC_VOLUME_BONUS, docs.length * CONFIDENCE_PER_DOC);
const enriched = docs.filter(d => d.contentFetched).length;
const enrichedBonus = Math.min(MAX_ENRICHMENT_BONUS, enriched * CONFIDENCE_PER_ENRICHED_DOC);
// EU stakeholder gets slightly lower confidence when there are no fpm docs
const euPenalty = perspective === 'eu-international' && b.fpm.length === 0 ? EU_NO_DATA_PENALTY : 0;
return Math.min(MAX_CONFIDENCE, Math.max(MIN_CONFIDENCE, BASE_CONFIDENCE + docBonus + enrichedBonus + euPenalty));
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
* Build AI-driven SWOT analyses for all 6 stakeholder perspectives.
*
* Returns `StakeholderSwot[]` ready for `generateStakeholderSwotSection()`.
* Each entry contains `AISwotEntry`-shaped data (which is compatible with the
* base `SwotEntry` shape used by the renderer).
*
* @param docs - Parliamentary documents relevant to the analysis topic
* @param topic - Focus topic for contextual framing (may be null)
* @param lang - Target language for stakeholder names and roles
*/
export function buildAISwotStakeholders(
docs: RawDocument[],
topic: string | null,
lang: Language,
): StakeholderSwot[] {
const perspectives: StakeholderPerspective[] = [
'government-coalition',
'opposition',
'eu-international',
'private-sector',
'civil-society',
'citizens-voters',
];
// Pre-bucket documents by type in a single pass for efficiency
const b = bucketDocs(docs);
const builders: Record<StakeholderPerspective, () => Pick<AISwotAnalysis, 'strengths' | 'weaknesses' | 'opportunities' | 'threats'>> = {
'government-coalition': () => buildGovernmentSwot(b, topic, lang),
opposition: () => buildOppositionSwot(b, topic, lang),
'eu-international': () => buildEUInternationalSwot(b, topic, lang),
'private-sector': () => buildPrivateSectorSwot(b, topic, lang),
'civil-society': () => buildCivilSocietySwot(b, topic, lang),
'citizens-voters': () => buildCitizensSwot(b, topic, lang),
};
const crossRefs = buildCrossReferences(b, topic);
// Localised labels for context metadata (with English fallback for safety)
const confidenceLabel = CONTEXT_LABELS.confidence[lang] ?? CONTEXT_LABELS.confidence.en;
const crossRefLabel = CONTEXT_LABELS.crossReferences[lang] ?? CONTEXT_LABELS.crossReferences.en;
return perspectives.map(p => {
const name = STAKEHOLDER_NAMES[p][lang];
const role = STAKEHOLDER_ROLES[p][lang];
const swotData = builders[p]();
const confidence = computeConfidence(docs, b, p);
// Attach confidence and crossReferences as context metadata (localised)
const contextParts: string[] = [];
contextParts.push(`${confidenceLabel}: ${Math.round(confidence * 100)}%`);
const ownRefs = crossRefs.filter(r => r.fromStakeholder === p || r.toStakeholder === p);
if (ownRefs.length > 0) {
contextParts.push(`${crossRefLabel}: ${ownRefs.length}`);
}
return {
name,
role,
swot: {
strengths: swotData.strengths,
weaknesses: swotData.weaknesses,
opportunities: swotData.opportunities,
threats: swotData.threats,
context: contextParts.join(' | '),
},
};
});
}
|