All files / scripts/analysis-framework political-threat-analysis.ts

88.05% Statements 177/201
72.22% Branches 130/180
100% Functions 26/26
92.13% Lines 164/178

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                                                                                          36x                 36x                 36x                 36x                 36x                 36x                         36x             36x               36x               36x               36x               36x                       39x       39x                     90x       30x                 6623x 6623x 30x 30x   6593x       180x 2266x       249x 4357x               30x     30x 30x   30x 10x   30x 11x   30x 1x   30x     30x 5x   30x 17x       30x       30x               4x 4x 4x 3x           1x 1x 1x           14x 14x           14x 13x 7x 6x       3x 3x 2x 1x           6x 6x 6x 4x 4x 4x 4x     36x     2x 2x 2x                       30x 30x   30x 30x   30x       30x 30x     30x   4x 4x   4x     1x 1x   1x     14x 14x 6x 8x 8x   14x     3x 3x   3x     6x 6x 2x 4x 4x   6x     2x 2x   2x       30x               30x   4x             1x             14x             3x             6x             2x                                     30x 30x 30x   30x                 30x   30x 30x 4x   26x 15x   11x     30x               189x   32x   31x   33x   31x   31x   31x                   189x 159x         30x   4x 4x   1x 1x   14x 14x   3x 3x   6x 6x   2x 2x     30x   30x                           36x                 36x                                                             30x   30x 180x 180x   30x 10x                 20x 1x     20x 30x     30x 30x 21x 33x       20x                                               9x 9x    
/**
 * @module analysis-framework/political-threat-analysis
 * @description PRIDES political threat analysis engine for parliamentary documents.
 *
 * Inspired by ISMS THREAT_MODEL.md (STRIDE framework, threat agent classification),
 * adapted for political intelligence analysis of Swedish parliamentary context.
 *
 * ## PRIDES Framework (Political STRIDE Adaptation)
 * | ISMS STRIDE              | Political PRIDES              |
 * |--------------------------|-------------------------------|
 * | Spoofing                 | Polarization                  |
 * | Tampering                | Regulatory Overreach          |
 * | Repudiation              | Institutional Erosion         |
 * | Information Disclosure   | Democratic Deficit            |
 * | Denial of Service        | Economic Disruption           |
 * | Elevation of Privilege   | Societal Impact               |
 *
 * ## Threat Agents
 * - Ruling coalition — Policy agenda risks, power concentration
 * - Opposition parties — Obstruction, populist pressure
 * - External actors — Foreign influence, EU regulatory pressure
 * - Special interests — Lobbying, regulatory capture
 * - Media — Narrative manipulation, selective reporting
 * - Institutional — Bureaucratic inertia, implementation failures
 *
 * The engine is **pure** — deterministic for the same input, no side effects.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import type { RawDocument, CIAContext } from '../data-transformers/types.js';
import type {
  PoliticalThreatAnalysis,
  PoliticalThreatProfile,
  PridesCategory,
  ThreatAgent,
  ThreatSeverity,
} from './methodology-types.js';
 
// ---------------------------------------------------------------------------
// Keyword banks per PRIDES category
// ---------------------------------------------------------------------------
 
/** P — Polarization: Intentional division, misleading rhetoric */
const POLARIZATION_KEYWORDS: readonly string[] = [
  'polarisering', 'splittring', 'oss och dem', 'extremism',
  'hatretorik', 'desinformation', 'propaganda', 'populism',
  'migrationsretorik', 'nationalistisk', 'sverigevänner', 'globalister',
  'polarization', 'division', 'disinformation', 'hate rhetoric',
  'us vs them', 'populist', 'nationalist rhetoric',
];
 
/** R — Regulatory Overreach: Abuse of legislative power, norm erosion */
const REGULATORY_OVERREACH_KEYWORDS: readonly string[] = [
  'demokratiunderskott', 'maktkoncentration', 'undantag från lagstiftning',
  'kringgå regler', 'undantas granskning', 'överprövar',
  'extraordinary powers', 'bypass parliament', 'circumvent legislation',
  'concentration of power', 'legislative overreach', 'executive overreach',
  'undantagstillstånd', 'nödbefogenheter',
];
 
/** I — Institutional Erosion: Weakening democratic institutions, accountability gaps */
const INSTITUTIONAL_EROSION_KEYWORDS: readonly string[] = [
  'urholkning', 'försvagning', 'KU-granskning', 'konstitutionsbrott',
  'bristande ansvar', 'accountability gap', 'institutional capture',
  'ansvarslöshet', 'bristande transparens', 'domstolspackning',
  'court packing', 'accountability deficit',
  'erosion of institutions', 'democratic backsliding', 'judicial independence',
];
 
/** D — Democratic Deficit: Lack of transparency, restricted public access */
const DEMOCRATIC_DEFICIT_KEYWORDS: readonly string[] = [
  'offentlighetsprincipen', 'sekretess', 'hemligstämplad', 'begränsad insyn',
  'informationsbegränsning', 'censur', 'pressfrihet', 'yttrandefrihet',
  'transparency', 'freedom of information', 'secrecy', 'censorship',
  'restricted access', 'press freedom', 'freedom of speech',
  'öppenhet', 'transparens', 'insyn', 'offentlighet',
];
 
/** E — Economic Disruption: Policy-driven economic harm, fiscal irresponsibility */
const ECONOMIC_DISRUPTION_KEYWORDS: readonly string[] = [
  'budgetkris', 'finanskris', 'ekonomisk destabilisering', 'statsbankrutt',
  'skuldkris', 'valutakris', 'inflation spiral', 'hyperinflation',
  'economic crisis', 'fiscal irresponsibility', 'debt crisis', 'budget crisis',
  'economic harm', 'fiscal disruption', 'austerity', 'economic shock',
  'statsfinansiell kris', 'budgetunderskott', 'skuldsättning',
];
 
/** S — Societal Impact: Disproportionate impact on vulnerable groups, rights erosion */
const SOCIETAL_IMPACT_KEYWORDS: readonly string[] = [
  'marginaliserade', 'utsatta grupper', 'diskriminering', 'rättighetsförlust',
  'ojämlikhet', 'fattigdom', 'barnfattigdom', 'hemlöshet', 'ofärd',
  'vulnerable groups', 'rights erosion', 'discrimination', 'inequality',
  'poverty', 'homelessness', 'marginalized communities', 'social exclusion',
  'grundläggande rättigheter', 'mänskliga rättigheter', 'human rights',
];
 
// ---------------------------------------------------------------------------
// Threat agent detection
// ---------------------------------------------------------------------------
 
/** Keywords identifying ruling coalition as threat agent */
const RULING_COALITION_INDICATORS: readonly string[] = [
  'regeringen', 'statsminister', 'finansminister', 'tidöavtal',
  'samarbetspartier', 'SD-stöd', 'alliansen', 'högeralliansen',
  'government', 'prime minister', 'ruling coalition', 'Tidö agreement',
];
 
/** Keywords identifying opposition parties as threat agent */
const OPPOSITION_INDICATORS: readonly string[] = [
  'opposition', 'oppositionsparti', 'S-ledd', 'vänsterblocket',
  'socialdemokraterna', 'vänsterpartiet', 'miljöpartiet',
  'opposition parties', 'left bloc', 'Social Democrats',
  'riksdagen avslår', 'motarbetar', 'blockerar', 'obstruerar',
];
 
/** Keywords identifying external actors as threat agent */
const EXTERNAL_ACTOR_INDICATORS: readonly string[] = [
  'EU-kommissionen', 'Bryssel', 'NATO', 'utländsk', 'Putin',
  'Ryssland', 'Kina', 'utländsk inblandning', 'foreign interference',
  'EU directive', 'Brussels', 'foreign actors', 'Russia', 'China',
  'geopolitisk', 'geopolitical',
];
 
/** Keywords identifying special interests as threat agent */
const SPECIAL_INTEREST_INDICATORS: readonly string[] = [
  'lobbyism', 'lobbying', 'branschintresse', 'särintresse',
  'näringsliv', 'industri', 'arbetsgivarorganisation', 'regulatory capture',
  'corporate influence', 'industry lobby', 'special interests',
  'finansiella intressen', 'partifinansiering',
];
 
/** Keywords identifying media as threat agent */
const MEDIA_INDICATORS: readonly string[] = [
  'mediabevakning', 'pressfrihet', 'narrativ', 'ryktesspridning',
  'desinformation', 'selektiv rapportering', 'mediaspinn',
  'media narrative', 'misinformation', 'selective reporting',
  'media manipulation', 'spin', 'fake news', 'alternativa fakta',
];
 
/** Keywords identifying institutional actors as threat agent */
const INSTITUTIONAL_INDICATORS: readonly string[] = [
  'myndighet', 'ämbetsverk', 'byråkrati', 'förvaltning',
  'implementeringsproblem', 'handläggningsproblem', 'processbrist',
  'agency', 'bureaucracy', 'implementation failure', 'administrative',
  'institutional inertia', 'bureaucratic resistance',
];
 
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
 
function getDocText(doc: RawDocument): string {
  const fullContentText = doc.fullContent
    ? doc.fullContent.replace(/<[^>]+>/g, ' ')
    : undefined;
 
  return [
    doc.titel, doc.rubrik, doc.undertitel, doc.title,
    doc.summary, doc.notis, doc.fullText, fullContentText,
  ].filter(Boolean).join(' ');
}
 
/**
 * Derive normalized document type from RawDocument.
 * Falls back from `doktyp` to `documentType`, lowercased and trimmed.
 */
function getDocType(doc: RawDocument): string {
  return String(doc.doktyp ?? doc.documentType ?? '').toLowerCase().trim();
}
 
function escapeRegExp(input: string): string {
  return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
 
/**
 * Word-boundary-aware keyword matching (ported from risk-assessment engine).
 * Short/uppercase abbreviations (e.g. "EU", "NATO") use word-boundary
 * matching to avoid false positives inside unrelated words.
 */
function keywordMatches(textLower: string, keyword: string): boolean {
  const isShortAbbreviation = /^[A-ZÅÄÖ]{2,4}$/.test(keyword);
  if (isShortAbbreviation) {
    const pattern = new RegExp(`\\b${escapeRegExp(keyword.toLowerCase())}\\b`, 'i');
    return pattern.test(textLower);
  }
  return textLower.includes(keyword.toLowerCase());
}
 
function containsAny(text: string, keywords: readonly string[]): boolean {
  const lower = text.toLowerCase();
  return keywords.some(kw => keywordMatches(lower, kw));
}
 
function countMatches(text: string, keywords: readonly string[]): number {
  const lower = text.toLowerCase();
  return keywords.filter(kw => keywordMatches(lower, kw)).length;
}
 
// ---------------------------------------------------------------------------
// Threat agent detection
// ---------------------------------------------------------------------------
 
function detectThreatAgents(doc: RawDocument, text: string): ThreatAgent[] {
  const agents: ThreatAgent[] = [];
 
  // Always include the most relevant institutional actor(s) based on document type
  const docType = getDocType(doc);
  const committee = doc.organ ?? '';
 
  if (containsAny(text, RULING_COALITION_INDICATORS) || ['prop', 'skr', 'sou'].includes(docType)) {
    agents.push('ruling-coalition');
  }
  if (containsAny(text, OPPOSITION_INDICATORS) || ['mot', 'ip', 'fr'].includes(docType)) {
    agents.push('opposition-parties');
  }
  if (containsAny(text, EXTERNAL_ACTOR_INDICATORS) || committee === 'UU' || committee === 'FöU') {
    agents.push('external-actors');
  }
  Iif (containsAny(text, SPECIAL_INTEREST_INDICATORS)) {
    agents.push('special-interests');
  }
  if (containsAny(text, MEDIA_INDICATORS)) {
    agents.push('media');
  }
  if (containsAny(text, INSTITUTIONAL_INDICATORS) || ['bet', 'ds', 'dir'].includes(docType)) {
    agents.push('institutional');
  }
 
  // Ensure at least one agent is always assigned
  Iif (agents.length === 0) {
    agents.push('ruling-coalition');
  }
 
  return [...new Set(agents)]; // deduplicate
}
 
// ---------------------------------------------------------------------------
// Per-PRIDES-category severity assessment
// ---------------------------------------------------------------------------
 
function assessPolarizationSeverity(text: string, cia: CIAContext | undefined): ThreatSeverity {
  const matches = countMatches(text, POLARIZATION_KEYWORDS);
  const stability = cia?.coalitionStability?.stabilityScore;
  if (matches >= 3 || (matches >= 2 && stability !== undefined && stability < 40)) return 'high';
  Eif (matches >= 2) return 'medium';
  if (matches >= 1) return 'low';
  return 'low';
}
 
function assessRegulatoryOverreachSeverity(text: string): ThreatSeverity {
  const matches = countMatches(text, REGULATORY_OVERREACH_KEYWORDS);
  Iif (matches >= 3) return 'critical';
  Eif (matches >= 2) return 'high';
  if (matches >= 1) return 'medium';
  return 'low';
}
 
function assessInstitutionalErosionSeverity(doc: RawDocument, text: string): ThreatSeverity {
  const matches = countMatches(text, INSTITUTIONAL_EROSION_KEYWORDS);
  const isKU = doc.organ === 'KU'; // KU is the institutional accountability body
 
  // Base thresholds: 3+ = critical, 2 = high, 1 = medium.
  // KU documents receive a severity boost so that critical remains reachable:
  // - KU with >= 2 matches -> critical
  // - KU with >= 1 match  -> high
  if (matches >= 3 || (isKU && matches >= 2)) return 'critical';
  if (matches >= 2 || (isKU && matches >= 1)) return 'high';
  if (matches >= 1) return 'medium';
  return 'low';
}
 
function assessDemocraticDeficitSeverity(doc: RawDocument, text: string): ThreatSeverity {
  const matches = countMatches(text, DEMOCRATIC_DEFICIT_KEYWORDS);
  if (doc.organ === 'KU' && matches >= 2) return 'critical';
  if (matches >= 3) return 'high';
  Eif (matches >= 2) return 'medium';
  if (matches >= 1) return 'low';
  return 'low';
}
 
function assessEconomicDisruptionSeverity(doc: RawDocument, text: string, cia: CIAContext | undefined): ThreatSeverity {
  const matches = countMatches(text, ECONOMIC_DISRUPTION_KEYWORDS);
  const stability = cia?.coalitionStability?.stabilityScore;
  if (doc.organ === 'FiU' && matches >= 2) return 'critical';
  Iif (matches >= 3 || (matches >= 2 && stability !== undefined && stability < 40)) return 'high';
  Iif (matches >= 2) return 'medium';
  Iif (matches >= 1) return 'low';
  return 'low';
}
 
const SOCIETAL_IMPACT_COMMITTEES = new Set(['SoU', 'SfU', 'AU']);
 
function assessSocietalImpactSeverity(doc: RawDocument, text: string): ThreatSeverity {
  const matches = countMatches(text, SOCIETAL_IMPACT_KEYWORDS);
  const committee = doc.organ ?? '';
  Eif (SOCIETAL_IMPACT_COMMITTEES.has(committee) && matches >= 2) return 'high';
  if (matches >= 3) return 'high';
  if (matches >= 2) return 'medium';
  if (matches >= 1) return 'low';
  return 'low';
}
 
// ---------------------------------------------------------------------------
// Observable indicator extraction
// ---------------------------------------------------------------------------
 
function extractIndicators(doc: RawDocument, category: PridesCategory, text: string): string[] {
  const indicators: string[] = [];
  const docId = doc.dok_id;
 
  Eif (docId) {
    indicators.push(`Parliamentary document ${docId} (${getDocType(doc) || 'unknown'}) identified as signal`);
  }
  Iif (doc.speeches && doc.speeches.length > 0) {
    const count = doc.speeches.length;
    indicators.push(`${count} parliamentary speech${count > 1 ? 'es' : ''} associated with this document`);
  }
  Eif (doc.organ) {
    indicators.push(`Committee involvement: ${doc.organ}`);
  }
 
  switch (category) {
    case 'polarization': {
      Eif (countMatches(text, POLARIZATION_KEYWORDS) > 0) {
        indicators.push('Language and framing may contribute to political polarization in this context');
      }
      break;
    }
    case 'regulatory-overreach': {
      Eif (countMatches(text, REGULATORY_OVERREACH_KEYWORDS) > 0) {
        indicators.push('Analysis suggests potential concentration of regulatory authority');
      }
      break;
    }
    case 'institutional-erosion': {
      const matches = countMatches(text, INSTITUTIONAL_EROSION_KEYWORDS);
      if (doc.organ === 'KU' && matches === 0) {
        indicators.push('Constitutional Committee (KU) context suggests potential accountability concern');
      } else if (Ematches > 0) {
        indicators.push('Analysis suggests potential gaps in institutional accountability');
      }
      break;
    }
    case 'democratic-deficit': {
      Eif (countMatches(text, DEMOCRATIC_DEFICIT_KEYWORDS) > 0) {
        indicators.push('Analysis suggests potential transparency or public access concerns');
      }
      break;
    }
    case 'economic-disruption': {
      const matches = countMatches(text, ECONOMIC_DISRUPTION_KEYWORDS);
      if (matches > 0) {
        indicators.push('Analysis suggests potential economic or fiscal disruption risk factors');
      } else if (Edoc.organ === 'FiU') {
        indicators.push('Finance Committee context suggests potential economic or fiscal disruption risk factors');
      }
      break;
    }
    case 'societal-impact': {
      Eif (countMatches(text, SOCIETAL_IMPACT_KEYWORDS) > 0) {
        indicators.push('Analysis suggests potential impact on vulnerable groups or fundamental rights');
      }
      break;
    }
  }
 
  return indicators;
}
 
// ---------------------------------------------------------------------------
// Democratic countermeasures
// ---------------------------------------------------------------------------
 
function getCountermeasures(category: PridesCategory): string[] {
  switch (category) {
    case 'polarization':
      return [
        'Public discourse institutions (SVT, SR) provide balanced media coverage',
        'Civil society organisations and fact-checkers challenge polarising narratives',
        'Cross-party parliamentary dialogue and consensus-seeking culture',
        'Swedish press freedom protections (Tryckfrihetsförordningen)',
      ];
    case 'regulatory-overreach':
      return [
        'Lagrådet (Council on Legislation) reviews proposed laws for constitutionality',
        'Constitutional Committee (KU) scrutinises government exercise of power',
        'Riksdag can vote no-confidence in the government (misstroendevotum)',
        'Ombudsman institutions (JO, JK) investigate complaints against government',
      ];
    case 'institutional-erosion':
      return [
        'Independent judiciary and administrative courts provide institutional check',
        'Parliamentary Ombudsman (JO) investigates institutional maladministration',
        'Riksdag constitutional review through KU provides political accountability',
        'ECHR and EU Charter of Fundamental Rights provide supranational protection',
      ];
    case 'democratic-deficit':
      return [
        'Offentlighetsprincipen (principle of public access) mandates transparency',
        'Data protection authority (IMY) enforces GDPR and privacy rights',
        'Freedom of the press constitutional protections (TF, YGL)',
        'Whistleblower protection legislation safeguards public interest disclosure',
      ];
    case 'economic-disruption':
      return [
        'Independent Riksbank provides monetary policy stabilisation',
        'EU Stability and Growth Pact constrains extreme fiscal departures',
        'Swedish Fiscal Policy Council (Finanspolitiska rådet) monitors fiscal discipline',
        'Cross-party budget framework prevents extreme year-on-year spending changes',
      ];
    case 'societal-impact':
      return [
        'Equality ombudsman (DO) enforces anti-discrimination legislation',
        'Swedish welfare state baseline protections provide safety net',
        'ECHR Article 14 and EU equality law provide rights protection',
        'Parliamentary debate and committee hearings surface societal impact concerns',
      ];
  }
}
 
// ---------------------------------------------------------------------------
// Rationale builder
// ---------------------------------------------------------------------------
 
function buildThreatRationale(
  doc: RawDocument,
  category: PridesCategory,
  severity: ThreatSeverity,
  text: string,
): string {
  const docType = getDocType(doc) || 'document';
  const committee = doc.organ ?? 'unknown';
  const severityLabel = severity.toUpperCase();
 
  const categoryDescriptions: Readonly<Record<PridesCategory, string>> = {
    'polarization': 'polarising rhetoric and divisive political framing',
    'regulatory-overreach': 'potential abuse of legislative or executive power',
    'institutional-erosion': 'signals of weakening democratic institutions or accountability gaps',
    'democratic-deficit': 'restricted transparency or limited public access to information',
    'economic-disruption': 'policy-driven economic harm or fiscal irresponsibility',
    'societal-impact': 'disproportionate impact on vulnerable groups or rights erosion',
  };
 
  const description = categoryDescriptions[category];
 
  const hasContent = (() => {
    if (doc.fullText || doc.fullContent) {
      return 'Full document content available.';
    }
    if (doc.summary) {
      return 'Summary-level content available; full text not available.';
    }
    return 'Based on metadata signals only; full text not available.';
  })();
 
  return `${severityLabel} PRIDES threat: ${description} detected in ${docType} document from committee ${committee}. ${hasContent} Document ${doc.dok_id ?? 'unknown'} presents observable signals matching this threat category based on ${text.length > 200 ? 'comprehensive' : 'limited'} text analysis.`;
}
 
// ---------------------------------------------------------------------------
// Single category analysis
// ---------------------------------------------------------------------------
 
function hasCategorySignals(category: PridesCategory, text: string, doc: RawDocument): boolean {
  switch (category) {
    case 'polarization':
      return countMatches(text, POLARIZATION_KEYWORDS) > 0;
    case 'regulatory-overreach':
      return countMatches(text, REGULATORY_OVERREACH_KEYWORDS) > 0;
    case 'institutional-erosion':
      return countMatches(text, INSTITUTIONAL_EROSION_KEYWORDS) > 0 || doc.organ === 'KU';
    case 'democratic-deficit':
      return countMatches(text, DEMOCRATIC_DEFICIT_KEYWORDS) > 0;
    case 'economic-disruption':
      return countMatches(text, ECONOMIC_DISRUPTION_KEYWORDS) > 0 || doc.organ === 'FiU';
    case 'societal-impact':
      return countMatches(text, SOCIETAL_IMPACT_KEYWORDS) > 0;
  }
}
 
function analyseSingleCategory(
  doc: RawDocument,
  cia: CIAContext | undefined,
  category: PridesCategory,
  text: string,
): PoliticalThreatAnalysis | null {
  if (!hasCategorySignals(category, text, doc)) {
    return null;
  }
 
  let severity: ThreatSeverity;
 
  switch (category) {
    case 'polarization':
      severity = assessPolarizationSeverity(text, cia);
      break;
    case 'regulatory-overreach':
      severity = assessRegulatoryOverreachSeverity(text);
      break;
    case 'institutional-erosion':
      severity = assessInstitutionalErosionSeverity(doc, text);
      break;
    case 'democratic-deficit':
      severity = assessDemocraticDeficitSeverity(doc, text);
      break;
    case 'economic-disruption':
      severity = assessEconomicDisruptionSeverity(doc, text, cia);
      break;
    case 'societal-impact':
      severity = assessSocietalImpactSeverity(doc, text);
      break;
  }
 
  const threatAgents = detectThreatAgents(doc, text);
 
  return {
    pridesCategory: category,
    threatAgents,
    severity,
    indicators: extractIndicators(doc, category, text),
    countermeasures: getCountermeasures(category),
    rationale: buildThreatRationale(doc, category, severity, text),
  };
}
 
// ---------------------------------------------------------------------------
// All PRIDES categories
// ---------------------------------------------------------------------------
 
const ALL_PRIDES_CATEGORIES: readonly PridesCategory[] = [
  'polarization',
  'regulatory-overreach',
  'institutional-erosion',
  'democratic-deficit',
  'economic-disruption',
  'societal-impact',
];
 
const SEVERITY_ORDER: Readonly<Record<ThreatSeverity, number>> = {
  critical: 4, high: 3, medium: 2, low: 1,
};
 
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
 
/**
 * Analyse a parliamentary document using the PRIDES political threat framework.
 *
 * Applies the ISMS-inspired PRIDES methodology (Political STRIDE adaptation)
 * to identify and characterise threats to democratic governance from the document.
 *
 * The function is **pure** — deterministic for the same input, no side effects.
 *
 * @param doc  - The parliamentary document to analyse
 * @param cia  - Optional CIA context (coalition data improves threat calibration)
 * @returns    Complete PRIDES threat profile
 *
 * @example
 * ```typescript
 * const profile = analysePoliticalThreats(doc, ciaContext);
 * console.log(profile.overallThreatLevel); // 'critical' | 'high' | 'medium' | 'low' | 'none'
 * console.log(profile.primaryThreat);      // dominant PRIDES category
 * ```
 */
export function analysePoliticalThreats(
  doc: RawDocument,
  cia?: CIAContext,
): PoliticalThreatProfile {
  const text = getDocText(doc);
 
  const threatAnalyses: PoliticalThreatAnalysis[] = ALL_PRIDES_CATEGORIES.map(category =>
    analyseSingleCategory(doc, cia, category, text)
  ).filter((a): a is PoliticalThreatAnalysis => a !== null);
 
  if (threatAnalyses.length === 0) {
    return {
      threatAnalyses: [],
      primaryThreat: null,
      overallThreatLevel: 'none',
      activeThreatAgents: [],
    };
  }
 
  // Sort by severity descending
  const sorted = [...threatAnalyses].sort(
    (a, b) => (SEVERITY_ORDER[b.severity] ?? 0) - (SEVERITY_ORDER[a.severity] ?? 0)
  );
 
  const primaryThreat = sorted[0]?.pridesCategory ?? null;
  const overallThreatLevel = sorted[0]?.severity ?? 'none';
 
  // Deduplicate threat agents across all analyses
  const agentSet = new Set<ThreatAgent>();
  for (const analysis of threatAnalyses) {
    for (const agent of analysis.threatAgents) {
      agentSet.add(agent);
    }
  }
 
  return {
    threatAnalyses,
    primaryThreat,
    overallThreatLevel,
    activeThreatAgents: [...agentSet],
  };
}
 
/**
 * Analyse threats for a specific PRIDES category only.
 *
 * Use when you need a targeted threat analysis for a single category
 * rather than the full PRIDES profile.
 *
 * @param doc      - The parliamentary document to analyse
 * @param category - The specific PRIDES category to analyse
 * @param cia      - Optional CIA context
 * @returns        Threat analysis for the specified category, or null if not detectable
 */
export function analyseSinglePridesCategory(
  doc: RawDocument,
  category: PridesCategory,
  cia?: CIAContext,
): PoliticalThreatAnalysis | null {
  const text = getDocText(doc);
  return analyseSingleCategory(doc, cia, category, text);
}