All files / scripts/pre-article-analysis markdown-serializer.ts

1.3% Statements 5/383
0% Branches 0/174
3.63% Functions 2/55
1.43% Lines 5/349

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                                                                                                                                                                                                                                                                                                                                  2x                             2x     2x     2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             135x              
/**
 * @module pre-article-analysis/markdown-serializer
 * @description Serializes analysis framework results as structured markdown
 * files for persistence in `analysis/daily/YYYY-MM-DD/`.
 *
 * Each output file follows the standard analysis template:
 * ```markdown
 * # [Analysis Type] — YYYY-MM-DD
 * **Generated**: YYYY-MM-DD HH:MM UTC
 * **Data Sources**: [list]
 * **Documents Analyzed**: N
 * **Confidence**: HIGH/MEDIUM/LOW
 * ## Summary / ## Detailed Analysis / ## Key Findings / ## Implications
 * ```
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
/* ── Inlined types (formerly from deleted analysis-framework/types module) ── */
 
interface SwotContribution {
  quadrant: string;
  text: string;
  forStakeholder: string;
}
 
interface DashboardMetric {
  label: string;
  value: number | string;
  unit?: string;
  metricName: string;
}
 
interface MindmapNode {
  label: string;
  children?: MindmapNode[];
}
 
interface PerspectiveAnalysis {
  lens: string;
  summary: string;
  impact: string;
  sentiment: string;
  swotContribution: SwotContribution[];
  dashboardMetrics: DashboardMetric[];
  mindmapNodes: MindmapNode[];
  confidence: number;
  keyActors: string[];
  relatedPolicies: string[];
}
 
interface DocumentLink {
  sourceId: string;
  targetId: string;
  type: string;
  description: string;
  confidence: number;
  reason: string;
}
 
interface DocumentAnalysisResult {
  document: {
    dok_id?: string;
    titel?: string;
    title?: string;
    doktyp?: string;
    organ?: string;
    committee?: string;
    datum?: string;
    intressent_namn?: string;
    author?: string;
    parti?: string;
    rm?: string;
    summary?: string;
    rubrik?: string;
    undertitel?: string;
    notis?: string;
    mottagare?: string;
    fullText?: string;
    fullContent?: string;
    [key: string]: unknown;
  };
  overallSignificance: number;
  perspectives: PerspectiveAnalysis[];
  crossDocumentLinks: DocumentLink[];
  keyInsights: string[];
  confidenceScore: number;
}
 
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
 
export interface SerializationContext {
  /** ISO date string, e.g. "2026-03-26" */
  date: string;
  /** UTC timestamp of generation */
  generatedAt: string;
  /** List of MCP tool names called to download data */
  dataSources: string[];
}
 
export interface SignificanceEntry {
  dok_id: string;
  title: string;
  score: number;
  doctype: string;
}
 
export interface RiskAssessmentResult {
  coalitionRiskScore: number;
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  riskSummary: string;
  anomalyFlags: Array<{ type: string; severity: string; description: string }>;
  implications: string[];
}
 
export interface SwotSummary {
  strengths: string[];
  weaknesses: string[];
  opportunities: string[];
  threats: string[];
  forStakeholder: string;
}
 
export interface CrossReferenceSummary {
  docCount: number;
  totalLinks: number;
  links: DocumentLink[];
}
 
export interface SynthesisSummary {
  totalDocs: number;
  executiveSummary: string;
  keyFindings: string[];
  topDocuments: SignificanceEntry[];
  overallConfidence: 'HIGH' | 'MEDIUM' | 'LOW';
  aggregateRiskLevel: string;
  /** When lookback was used, the actual date of the data (YYYY-MM-DD).
   *  `null` when documents match the requested article date exactly. */
  dataFreshness: string | null;
}
 
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
 
/**
 * Map a numeric confidence score (0–100) to a categorical label.
 * - ≥70: HIGH — strong evidence, full-text content available for most documents
 * - 40–69: MEDIUM — moderate evidence, mix of full-text and metadata-only
 * - <40: LOW — weak evidence, metadata-only documents or small batch
 */
function confidenceLabel(score: number): 'HIGH' | 'MEDIUM' | 'LOW' {
  if (score >= 70) return 'HIGH';
  if (score >= 40) return 'MEDIUM';
  return 'LOW';
}
 
/** Maximum number of documents shown in the detailed analysis section */
const MAX_DETAILED_RESULTS = 20;
 
function significanceLabel(score: number): string {
  if (score >= 8) return '🔴 Critical';
  if (score >= 6) return '🟠 High';
  if (score >= 4) return '🟡 Medium';
  return '🟢 Low';
}
 
/**
 * Prefix used to tag policy domain classifications in keyInsights.
 *
 * Keep all parsing in this file derived from this constant so a future prefix
 * change does not silently drift from regex-based extraction logic.
 */
export const POLICY_DOMAIN_INSIGHT_PREFIX = 'Policy domain:';
 
function escapeRegExp(value: string): string {
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
 
const POLICY_DOMAIN_INSIGHT_REGEX = new RegExp(
  `^${escapeRegExp(POLICY_DOMAIN_INSIGHT_PREFIX)}\\s*(.+?)\\s*(?:\\(|$)`,
  'i',
);
 
function extractPolicyDomainFromInsight(insight: string): string | null {
  const match = POLICY_DOMAIN_INSIGHT_REGEX.exec(insight.trim());
  return match?.[1]?.trim() || null;
}
 
function escapeMarkdownTableCell(value: string): string {
  return value
    .replace(/\\/g, '\\\\')
    .replace(/\r?\n/g, ' ')
    .replace(/\|/g, '\\|')
    .trim();
}
 
/** Escape user-sourced text for safe inline Markdown rendering. */
function escapeMarkdownInline(value: string): string {
  return value
    .replace(/\r?\n/g, ' ')
    .replace(/[#*_`[\]<>|\\~]/g, '\\$&')
    .trim();
}
 
 
function frontmatter(ctx: SerializationContext, title: string, docCount: number, confidenceScore: number): string {
  return [
    `# ${title} — ${ctx.date}`,
    '',
    `**Generated**: ${ctx.generatedAt}`,
    `**Data Sources**: ${ctx.dataSources.join(', ')}`,
    `**Documents Analyzed**: ${docCount}`,
    `**Confidence**: ${confidenceLabel(confidenceScore)}`,
    `**Produced By**: pre-article-analysis script (automated data pipeline)`,
    '',
    `> ⚠️ **Script-Generated Analysis**: This file was produced by the automated data pipeline (\`scripts/pre-article-analysis.ts\`). It contains structured data extraction and basic statistical analysis only. For deep political intelligence with evidence-based claims, Mermaid diagrams, and multi-framework analysis, this file should be enriched or replaced by AI-driven analysis following \`analysis/methodologies/ai-driven-analysis-guide.md\`.`,
    '',
  ].join('\n');
}
 
// ---------------------------------------------------------------------------
// Data-download manifest
// ---------------------------------------------------------------------------
 
export function serializeDataManifest(
  ctx: SerializationContext,
  docCounts: Record<string, number>,
  dateFilteredTotal?: number,
): string {
  const totalDocs = Object.values(docCounts).reduce((a, b) => a + b, 0);
  const analyzedCount = dateFilteredTotal ?? totalDocs;
  const lines: string[] = [
    frontmatter(ctx, 'Data Download Manifest', analyzedCount, 100),
    '## Summary',
    '',
    `Downloaded **${totalDocs}** documents (session-wide) from ${ctx.dataSources.length} MCP data sources.`,
    '',
  ];
 
  if (dateFilteredTotal !== undefined) {
    lines.push(`After date filtering to **${ctx.date}**: **${dateFilteredTotal}** documents selected for analysis.`, '');
  }
 
  lines.push('## Document Counts by Type', '');
 
  for (const [type, count] of Object.entries(docCounts)) {
    lines.push(`- **${type}**: ${count} documents`);
  }
 
  lines.push('', '## Data Quality Notes', '', 'All documents sourced from official riksdag-regering-mcp API.');
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Classification results
// ---------------------------------------------------------------------------
 
export function serializeClassificationResults(
  ctx: SerializationContext,
  results: DocumentAnalysisResult[],
): string {
  const avgConfidence =
    results.length > 0
      ? results.reduce((sum, r) => sum + r.confidenceScore, 0) / results.length
      : 0;
 
  const lines: string[] = [
    frontmatter(ctx, 'Political Classification Results', results.length, avgConfidence),
    '## Summary',
    '',
    `Classified **${results.length}** parliamentary documents by sensitivity, impact, urgency, and domain.`,
    '',
    '## Detailed Analysis',
    '',
  ];
 
  for (const result of results.slice(0, MAX_DETAILED_RESULTS)) {
    const title = result.document.titel || result.document.title || result.document.dok_id || 'Unknown';
    const dokId = result.document.dok_id || 'N/A';
    // Domains: try perspectives first, then keyInsights (which may contain domain info)
    let domains = result.perspectives
      .flatMap(p => p.relatedPolicies)
      .filter((v, i, arr) => arr.indexOf(v) === i)
      .slice(0, 3);
    if (domains.length === 0 && result.keyInsights.length > 0) {
      const domainInsight = result.keyInsights
        .map(insight => insight.trim())
        .find(insight => POLICY_DOMAIN_INSIGHT_REGEX.test(insight));
      if (domainInsight) {
        const raw = extractPolicyDomainFromInsight(domainInsight);
        if (raw) {
          domains = raw.split(',').map(d => d.trim()).slice(0, 3);
        }
      }
    }
 
    lines.push(`### ${title}`);
    lines.push(`- **dok_id**: ${dokId}`);
    lines.push(`- **Type**: ${result.document.doktyp || 'unknown'}`);
    lines.push(`- **Significance**: ${significanceLabel(result.overallSignificance)} (${result.overallSignificance}/10)`);
    lines.push(`- **Domains**: ${domains.join(', ') || 'General'}`);
    lines.push(`- **Confidence**: ${confidenceLabel(result.confidenceScore)} (${Math.round(result.confidenceScore)}%)`);
    lines.push('');
  }
 
  lines.push('## Key Findings', '');
  const topDocs = [...results].sort((a, b) => b.overallSignificance - a.overallSignificance).slice(0, 5);
  topDocs.forEach((r, i) => {
    const title = r.document.titel || r.document.title || r.document.dok_id || 'Unknown';
    lines.push(`${i + 1}. **${title}** (dok_id: ${r.document.dok_id || 'N/A'}) — Significance: ${r.overallSignificance}/10`);
  });
 
  lines.push('', '## Implications', '');
  lines.push('Classification drives article prioritisation. High-significance documents should receive deep-inspection treatment.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push(`Classification confidence: ${confidenceLabel(avgConfidence)}. Higher confidence when full-text content is available.`);
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Risk assessment
// ---------------------------------------------------------------------------
 
export function serializeRiskAssessment(
  ctx: SerializationContext,
  docCount: number,
  risk: RiskAssessmentResult,
): string {
  const confidenceScore = risk.riskLevel === 'LOW' ? 80 : risk.riskLevel === 'MEDIUM' ? 60 : 40;
 
  const lines: string[] = [
    frontmatter(ctx, 'Political Risk Assessment', docCount, confidenceScore),
    '## Summary',
    '',
    risk.riskSummary,
    '',
    '## Detailed Analysis',
    '',
    `**Coalition Risk Score**: ${risk.coalitionRiskScore}/100`,
    `**Risk Level**: ${risk.riskLevel}`,
    '',
    '### Anomaly Flags',
    '',
  ];
 
  if (risk.anomalyFlags.length > 0) {
    for (const flag of risk.anomalyFlags) {
      lines.push(`- **[${flag.severity}]** ${flag.type}: ${flag.description}`);
    }
  } else {
    lines.push('No anomalous patterns detected in current data.');
  }
 
  lines.push('', '## Key Findings', '');
  lines.push(`1. Coalition stability at risk score **${risk.coalitionRiskScore}** (${risk.riskLevel})`);
  if (risk.anomalyFlags.length > 0) {
    lines.push(`2. **${risk.anomalyFlags.length}** anomaly flag(s) detected requiring monitoring`);
  }
 
  lines.push('', '## Implications', '');
  for (const impl of risk.implications) {
    lines.push(`- ${impl}`);
  }
 
  lines.push('', '## Data Quality Notes', '');
  lines.push('Risk assessment derived from CIA coalition metrics and document significance scores.');
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// SWOT analysis
// ---------------------------------------------------------------------------
 
export function serializeSwotAnalysis(
  ctx: SerializationContext,
  docCount: number,
  swots: SwotSummary[],
): string {
  const hasContent = swots.length > 0;
  const lines: string[] = [
    frontmatter(ctx, 'Political SWOT Analysis', docCount, hasContent ? 70 : 20),
    '## Summary',
    '',
  ];
 
  if (!hasContent) {
    lines.push(
      `> ⚠️ **No SWOT entries generated**: The automated data pipeline found ${docCount} documents but could not extract SWOT contributions from metadata alone. Deep SWOT analysis requires AI-driven per-document analysis following \`analysis/methodologies/political-swot-framework.md\`.`,
      '',
      'AI agentic workflows should replace this file with multi-framework SWOT analysis including:',
      '- Evidence-backed strengths/weaknesses/opportunities/threats per political actor',
      '- Cross-SWOT interference patterns',
      '- TOWS matrix and scenario generation',
      '- Color-coded Mermaid diagrams with real data',
    );
  } else {
    lines.push(`Generated SWOT analysis for **${swots.length}** political actor(s) based on ${docCount} documents.`);
  }
 
  lines.push('', '## Detailed Analysis', '');
 
  for (const swot of swots) {
    lines.push(`### ${swot.forStakeholder}`, '');
 
    lines.push('**Strengths**');
    swot.strengths.forEach(s => lines.push(`- ${s}`));
    lines.push('');
 
    lines.push('**Weaknesses**');
    swot.weaknesses.forEach(s => lines.push(`- ${s}`));
    lines.push('');
 
    lines.push('**Opportunities**');
    swot.opportunities.forEach(s => lines.push(`- ${s}`));
    lines.push('');
 
    lines.push('**Threats**');
    swot.threats.forEach(s => lines.push(`- ${s}`));
    lines.push('');
  }
 
  lines.push('## Key Findings', '');
  if (hasContent) {
    lines.push('1. SWOT entries derived from all six perspective analyses across downloaded documents.');
  } else {
    lines.push('1. No SWOT entries could be derived from document metadata alone — AI analysis required.');
  }
 
  lines.push('', '## Implications', '');
  lines.push('SWOT insights should inform stakeholder framing in generated articles.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push(hasContent
    ? 'SWOT confidence is proportional to document richness (full-text vs metadata-only).'
    : 'SWOT confidence: LOW. Script pipeline provides structured data only — AI analysis is required for political SWOT insights.');
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Threat analysis
// ---------------------------------------------------------------------------
 
export function serializeThreatAnalysis(
  ctx: SerializationContext,
  results: DocumentAnalysisResult[],
): string {
  const threatEntries = results.flatMap(r =>
    r.perspectives.flatMap(p =>
      p.swotContribution
        .filter(c => c.quadrant === 'threat')
        .map(c => ({ title: r.document.titel || r.document.title || r.document.dok_id || 'Unknown', text: c.text, forStakeholder: c.forStakeholder }))
    )
  );
 
  const avgConfidence =
    results.length > 0
      ? results.reduce((sum, r) => sum + r.confidenceScore, 0) / results.length
      : 0;
 
  const hasContent = threatEntries.length > 0;
 
  const lines: string[] = [
    frontmatter(ctx, 'Political Threat Analysis', results.length, hasContent ? avgConfidence : Math.min(avgConfidence, 20)),
    '## Summary',
    '',
  ];
 
  if (!hasContent) {
    lines.push(
      `> ⚠️ **No threat indicators extracted**: The automated data pipeline found ${results.length} documents but could not identify specific threat indicators from metadata alone. Deep threat analysis requires AI-driven per-document analysis following \`analysis/methodologies/political-threat-framework.md\`.`,
      '',
      'AI agentic workflows should replace this file with multi-framework threat analysis including:',
      '- Attack Tree analysis with threat actors and vectors',
      '- Kill Chain analysis of political threat progressions',
      '- Diamond Model threat actor characterization',
      '- Political Threat Taxonomy classification',
      '- Color-coded Mermaid diagrams with evidence-based data',
    );
  } else {
    lines.push(`Identified **${threatEntries.length}** threat indicators across ${results.length} documents.`);
  }
 
  lines.push('', '## Detailed Analysis', '');
 
  const grouped = new Map<string, string[]>();
  for (const entry of threatEntries) {
    const arr = grouped.get(entry.forStakeholder) ?? [];
    arr.push(`[${entry.title}] ${entry.text}`);
    grouped.set(entry.forStakeholder, arr);
  }
 
  for (const [stakeholder, threats] of grouped) {
    lines.push(`### Threats for: ${stakeholder}`, '');
    threats.slice(0, 5).forEach(t => lines.push(`- ${t}`));
    lines.push('');
  }
 
  lines.push('## Key Findings', '');
  if (hasContent) {
    lines.push(`1. **${threatEntries.length}** threat indicators identified targeting ${grouped.size} stakeholder group(s)`);
  } else {
    lines.push('1. No threat indicators could be derived from document metadata alone — AI analysis required.');
  }
 
  lines.push('', '## Implications', '');
  lines.push('Threat analysis should inform risk-focused article framing and editorial prioritisation.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push(hasContent
    ? `Analysis confidence: ${confidenceLabel(avgConfidence)}.`
    : `Analysis confidence: LOW. Script pipeline provides structured data only — AI analysis is required for political threat assessment.`);
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Stakeholder perspectives
// ---------------------------------------------------------------------------
 
export function serializeStakeholderPerspectives(
  ctx: SerializationContext,
  results: DocumentAnalysisResult[],
): string {
  const avgConfidence =
    results.length > 0
      ? results.reduce((sum, r) => sum + r.confidenceScore, 0) / results.length
      : 0;
 
  // Aggregate perspectives by lens across all documents
  const lensMap = new Map<string, PerspectiveAnalysis[]>();
  for (const result of results) {
    for (const p of result.perspectives) {
      const arr = lensMap.get(p.lens) ?? [];
      arr.push(p);
      lensMap.set(p.lens, arr);
    }
  }
 
  const lines: string[] = [
    frontmatter(ctx, 'Stakeholder Perspective Analysis', results.length, avgConfidence),
    '## Summary',
    '',
    `Applied **6 analysis lenses** to **${results.length}** documents.`,
    '',
    '## Detailed Analysis',
    '',
  ];
 
  const lensEmoji: Record<string, string> = {
    government: '🏛️',
    opposition: '⚖️',
    citizen: '👥',
    economic: '💰',
    international: '🌍',
    media: '📰',
  };
 
  for (const [lens, perspectives] of lensMap) {
    const emoji = lensEmoji[lens] || '🔍';
    const high = perspectives.filter(p => p.impact === 'high').length;
    const avgConf = perspectives.reduce((s, p) => s + p.confidence, 0) / perspectives.length;
    const topActors = [...new Set(perspectives.flatMap(p => p.keyActors))].slice(0, 5);
 
    lines.push(`### ${emoji} ${lens.charAt(0).toUpperCase() + lens.slice(1)} Perspective`, '');
    lines.push(`- **Documents with High Impact**: ${high}/${perspectives.length}`);
    lines.push(`- **Avg Confidence**: ${Math.round(avgConf)}%`);
    lines.push(`- **Key Actors**: ${topActors.join(', ') || 'N/A'}`);
    lines.push('');
 
    // Show top 3 summaries
    const topThree = [...perspectives].sort((a, b) => b.confidence - a.confidence).slice(0, 3);
    for (const p of topThree) {
      if (p.summary) {
        lines.push(`> ${p.summary}`);
        lines.push('');
      }
    }
  }
 
  lines.push('## Key Findings', '');
  lines.push('1. All six stakeholder perspectives applied consistently across the document batch.');
  lines.push('2. Cross-perspective conflicts indicate politically contentious documents.');
 
  lines.push('', '## Implications', '');
  lines.push('Perspective analysis feeds directly into article stakeholder framing and balance.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push(`Aggregate confidence: ${confidenceLabel(avgConfidence)}.`);
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Significance scoring
// ---------------------------------------------------------------------------
 
export function serializeSignificanceScoring(
  ctx: SerializationContext,
  entries: SignificanceEntry[],
): string {
  const lines: string[] = [
    frontmatter(ctx, 'Document Significance Scoring', entries.length, 80),
    '## Summary',
    '',
    `Scored **${entries.length}** documents for political significance (0–10 scale).`,
    '',
    '## Detailed Analysis',
    '',
    '| Score | Level | Type | dok_id | Title |',
    '|-------|-------|------|--------|-------|',
  ];
 
  const sorted = [...entries].sort((a, b) => b.score - a.score);
  for (const entry of sorted.slice(0, 30)) {
    const level = escapeMarkdownTableCell(significanceLabel(entry.score).replace(/🔴|🟠|🟡|🟢/g, '').trim());
    const titleValue = entry.title.length > 50 ? entry.title.slice(0, 47) + '...' : entry.title;
    const doctype = escapeMarkdownTableCell(entry.doctype);
    const dokId = escapeMarkdownTableCell(entry.dok_id);
    const title = escapeMarkdownTableCell(titleValue);
    lines.push(`| ${entry.score}/10 | ${level} | ${doctype} | ${dokId} | ${title} |`);
  }
 
  lines.push('', '## Key Findings', '');
  const critical = sorted.filter(e => e.score >= 8);
  lines.push(`1. **${critical.length}** document(s) rated Critical (score ≥ 8)`);
  const high = sorted.filter(e => e.score >= 6 && e.score < 8);
  lines.push(`2. **${high.length}** document(s) rated High (score 6–7)`);
 
  lines.push('', '## Implications', '');
  lines.push('High-significance documents should be prioritised for deep-inspection article generation.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push('Significance scores use document type, committee tier, domain breadth, coalition context, and content richness.');
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Cross-reference map
// ---------------------------------------------------------------------------
 
export function serializeCrossReferenceMap(
  ctx: SerializationContext,
  summary: CrossReferenceSummary,
): string {
  const lines: string[] = [
    frontmatter(ctx, 'Cross-Reference Map', summary.docCount, 75),
    '## Summary',
    '',
    `Detected **${summary.totalLinks}** cross-document relationships.`,
    '',
    '## Detailed Analysis',
    '',
  ];
 
  if (summary.links.length === 0) {
    lines.push('No cross-document relationships detected in current batch.');
  } else {
    const byType = new Map<string, DocumentLink[]>();
    for (const link of summary.links) {
      const arr = byType.get(link.type) ?? [];
      arr.push(link);
      byType.set(link.type, arr);
    }
 
    for (const [type, links] of byType) {
      lines.push(`### ${type}`, '');
      for (const link of links.slice(0, 10)) {
        lines.push(`- **${link.sourceId}** → **${link.targetId}** (confidence: ${link.confidence}%)`);
        lines.push(`  _${link.reason}_`);
      }
      lines.push('');
    }
  }
 
  lines.push('## Key Findings', '');
  lines.push(`1. **${summary.totalLinks}** inter-document relationships mapped`);
 
  lines.push('', '## Implications', '');
  lines.push('Cross-references enrich article narratives by linking related legislative developments.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push('Cross-reference confidence is driven by shared policy domains and textual similarity.');
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Synthesis summary
// ---------------------------------------------------------------------------
 
export function serializeSynthesisSummary(
  ctx: SerializationContext,
  synthesis: SynthesisSummary,
): string {
  const confScore = synthesis.overallConfidence === 'HIGH' ? 80 : synthesis.overallConfidence === 'MEDIUM' ? 55 : 30;
 
  const lines: string[] = [
    frontmatter(ctx, 'Analysis Synthesis Summary', synthesis.totalDocs, confScore),
    '## Summary',
    '',
    synthesis.executiveSummary,
    '',
    '## Key Findings',
    '',
  ];
 
  synthesis.keyFindings.forEach((f, i) => lines.push(`${i + 1}. ${f}`));
 
  lines.push('', '## Top Documents by Significance', '', '| Score | Type | dok_id | Title |', '|-------|------|--------|-------|');
  for (const doc of synthesis.topDocuments.slice(0, 10)) {
    const titleValue = doc.title.length > 50 ? doc.title.slice(0, 47) + '...' : doc.title;
    const doctype = escapeMarkdownTableCell(doc.doctype);
    const dokId = escapeMarkdownTableCell(doc.dok_id);
    const title = escapeMarkdownTableCell(titleValue);
    lines.push(`| ${doc.score}/10 | ${doctype} | ${dokId} | ${title} |`);
  }
 
  lines.push('', '## Implications', '');
  lines.push(`Overall political risk level: **${synthesis.aggregateRiskLevel}**`);
  lines.push('Articles should reference this synthesis to ensure analytical depth and consistency.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push(`Overall confidence: **${synthesis.overallConfidence}**. All analysis results are available in sibling files.`);
  if (synthesis.dataFreshness) {
    lines.push(`**Data Freshness**: Documents sourced from **${synthesis.dataFreshness}** via lookback fallback (article date: ${ctx.date}).`);
  }
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Per-document analysis (full AI-quality SWOT + intelligence per document)
// ---------------------------------------------------------------------------
 
/**
 * Serialize a per-document analysis markdown file.
 *
 * Each document gets its own analysis file with:
 * - Full document metadata
 * - Detailed SWOT analysis
 * - Multi-lens stakeholder perspective analysis
 * - Significance scoring factors
 * - Cross-document references (where available)
 * - Key insights
 * - Data quality / methodology notes
 *
 * Note: Explicit risk indicator extraction and implications sections are
 * produced at the synthesis level rather than by this per-document serializer.
 */
export function serializeDocumentAnalysis(
  ctx: SerializationContext,
  result: DocumentAnalysisResult,
): string {
  const doc = result.document;
  const title = escapeMarkdownInline(doc.titel || doc.title || doc.dok_id || 'Unknown Document');
  const dokId = escapeMarkdownInline(doc.dok_id || 'N/A');
  const docType = escapeMarkdownInline(doc.doktyp || 'unknown');
  const committee = escapeMarkdownInline(doc.organ || doc.committee || 'N/A');
  const date = escapeMarkdownInline(doc.datum || ctx.date);
  const author = escapeMarkdownInline(doc.intressent_namn || doc.author || 'N/A');
  const party = escapeMarkdownInline(doc.parti || 'N/A');
  const rm = escapeMarkdownInline(doc.rm || 'N/A');
 
  const lines: string[] = [
    `# Document Analysis: ${title}`,
    '',
    `**Generated**: ${ctx.generatedAt}`,
    `**dok_id**: ${dokId}`,
    `**Document Type**: ${docType}`,
    `**Committee**: ${committee}`,
    `**Date**: ${date}`,
    `**Author**: ${author}`,
    `**Party**: ${party}`,
    `**Riksmöte**: ${rm}`,
    `**Significance**: ${significanceLabel(result.overallSignificance)} (${result.overallSignificance}/10)`,
    `**Confidence**: ${confidenceLabel(result.confidenceScore)} (${Math.round(result.confidenceScore)}%)`,
    '',
    '---',
    '',
  ];
 
  // ── Executive Summary ──────────────────────────────────────────────────
  lines.push('## Executive Summary', '');
  if (result.keyInsights.length > 0) {
    for (const insight of result.keyInsights) {
      lines.push(`- ${escapeMarkdownInline(insight)}`);
    }
  } else {
    lines.push('No key insights extracted — document may be metadata-only.');
  }
  lines.push('');
 
  // ── Document Content Summary ───────────────────────────────────────────
  lines.push('## Document Content', '');
  if (doc.summary) {
    lines.push(`**Summary**: ${escapeMarkdownInline(doc.summary)}`);
    lines.push('');
  }
  if (doc.rubrik) {
    lines.push(`**Rubrik**: ${escapeMarkdownInline(doc.rubrik)}`);
    lines.push('');
  }
  if (doc.undertitel) {
    lines.push(`**Undertitel**: ${escapeMarkdownInline(doc.undertitel)}`);
    lines.push('');
  }
  if (doc.notis) {
    lines.push(`**Notis**: ${escapeMarkdownInline(doc.notis)}`);
    lines.push('');
  }
  if (doc.mottagare) {
    lines.push(`**Mottagare (Recipient)**: ${escapeMarkdownInline(doc.mottagare)}`);
    lines.push('');
  }
  const hasFullText = !!(doc.fullText || doc.fullContent);
  lines.push(`**Full-text available**: ${hasFullText ? 'Yes ✅' : 'No — metadata-only ⚠️'}`);
  lines.push('');
 
  // ── SWOT Analysis ──────────────────────────────────────────────────────
  lines.push('## SWOT Analysis', '');
  const swotMap = new Map<string, { strengths: string[]; weaknesses: string[]; opportunities: string[]; threats: string[] }>();
  for (const p of result.perspectives) {
    for (const c of p.swotContribution) {
      if (!swotMap.has(c.forStakeholder)) {
        swotMap.set(c.forStakeholder, { strengths: [], weaknesses: [], opportunities: [], threats: [] });
      }
      const entry = swotMap.get(c.forStakeholder)!;
      switch (c.quadrant) {
        case 'strength': entry.strengths.push(c.text); break;
        case 'weakness': entry.weaknesses.push(c.text); break;
        case 'opportunity': entry.opportunities.push(c.text); break;
        case 'threat': entry.threats.push(c.text); break;
      }
    }
  }
 
  if (swotMap.size === 0) {
    lines.push('_No SWOT contributions extracted. Document may lack sufficient content for structured analysis._');
    lines.push('');
  }
 
  for (const [stakeholder, swot] of swotMap) {
    lines.push(`### SWOT: ${escapeMarkdownInline(stakeholder)}`, '');
 
    lines.push('#### Strengths 💪');
    if (swot.strengths.length > 0) {
      [...new Set(swot.strengths)].forEach(s => lines.push(`- ${escapeMarkdownInline(s)}`));
    } else {
      lines.push('- _No strengths identified_');
    }
    lines.push('');
 
    lines.push('#### Weaknesses ⚠️');
    if (swot.weaknesses.length > 0) {
      [...new Set(swot.weaknesses)].forEach(s => lines.push(`- ${escapeMarkdownInline(s)}`));
    } else {
      lines.push('- _No weaknesses identified_');
    }
    lines.push('');
 
    lines.push('#### Opportunities 🌟');
    if (swot.opportunities.length > 0) {
      [...new Set(swot.opportunities)].forEach(s => lines.push(`- ${escapeMarkdownInline(s)}`));
    } else {
      lines.push('- _No opportunities identified_');
    }
    lines.push('');
 
    lines.push('#### Threats 🔴');
    if (swot.threats.length > 0) {
      [...new Set(swot.threats)].forEach(s => lines.push(`- ${escapeMarkdownInline(s)}`));
    } else {
      lines.push('- _No threats identified_');
    }
    lines.push('');
  }
 
  // ── Stakeholder Perspective Analysis ───────────────────────────────────
  lines.push('## Stakeholder Perspective Analysis', '');
 
  const lensEmoji: Record<string, string> = {
    government: '🏛️',
    opposition: '⚖️',
    citizen: '👥',
    economic: '💰',
    international: '🌍',
    media: '📰',
  };
 
  for (const p of result.perspectives) {
    const emoji = lensEmoji[p.lens] || '🔍';
    lines.push(`### ${emoji} ${p.lens.charAt(0).toUpperCase() + p.lens.slice(1)} Perspective`, '');
    lines.push(`- **Impact**: ${escapeMarkdownInline(p.impact)}`);
    lines.push(`- **Sentiment**: ${escapeMarkdownInline(p.sentiment)}`);
    lines.push(`- **Confidence**: ${Math.round(p.confidence)}%`);
    lines.push(`- **Key Actors**: ${p.keyActors.map(a => escapeMarkdownInline(a)).join(', ') || 'N/A'}`);
    lines.push(`- **Related Policies**: ${p.relatedPolicies.map(r => escapeMarkdownInline(r)).join(', ') || 'N/A'}`);
    lines.push('');
    if (p.summary) {
      lines.push(`> ${escapeMarkdownInline(p.summary)}`);
      lines.push('');
    }
 
    // Dashboard metrics
    if (p.dashboardMetrics.length > 0) {
      lines.push('**Dashboard Metrics**:');
      for (const m of p.dashboardMetrics) {
        lines.push(`- ${escapeMarkdownInline(m.metricName)}: ${m.value}${m.unit ? ' ' + escapeMarkdownInline(m.unit) : ''}`);
      }
      lines.push('');
    }
  }
 
  // ── Cross-Document References ──────────────────────────────────────────
  lines.push('## Cross-Document References', '');
  if (result.crossDocumentLinks.length > 0) {
    for (const link of result.crossDocumentLinks) {
      lines.push(`- **${escapeMarkdownInline(link.type)}**: ${escapeMarkdownInline(link.sourceId)} → ${escapeMarkdownInline(link.targetId)} (confidence: ${link.confidence}%)`);
      lines.push(`  _${escapeMarkdownInline(link.reason)}_`);
    }
  } else {
    lines.push('_No cross-document references detected for this document._');
  }
  lines.push('');
 
  // ── Significance Assessment ────────────────────────────────────────────
  lines.push('## Significance Assessment', '');
  lines.push(`**Overall Score**: ${result.overallSignificance}/10 — ${significanceLabel(result.overallSignificance)}`);
  lines.push('');
  lines.push('**Scoring Factors**:');
  lines.push(`- Document type tier (${docType})`);
  lines.push(`- Committee tier (${committee})`);
  const domains = [...new Set(result.perspectives.flatMap(p => p.relatedPolicies))].slice(0, 5);
  lines.push(`- Policy domain breadth: ${domains.length} domain(s) — ${domains.join(', ') || 'N/A'}`);
  lines.push(`- Content richness: ${hasFullText ? 'Full-text available' : 'Metadata-only'}`);
  lines.push(`- Perspective impact: ${result.perspectives.filter(p => p.impact === 'high').length}/6 high-impact perspectives`);
  lines.push('');
 
  // ── Key Insights ───────────────────────────────────────────────────────
  lines.push('## Key Insights', '');
  if (result.keyInsights.length > 0) {
    result.keyInsights.forEach((insight, i) => lines.push(`${i + 1}. ${escapeMarkdownInline(insight)}`));
  } else {
    lines.push('_No key insights extracted._');
  }
  lines.push('');
 
  // ── Data Quality Notes ─────────────────────────────────────────────────
  lines.push('## Data Quality Notes', '');
  lines.push(`- **Analysis confidence**: ${confidenceLabel(result.confidenceScore)} (${Math.round(result.confidenceScore)}%)`);
  lines.push(`- **Full-text content**: ${hasFullText ? 'Available — high confidence' : 'Unavailable — analysis based on metadata only'}`);
  lines.push(`- **Data sources**: ${ctx.dataSources.map(escapeMarkdownInline).join(', ')}`);
  lines.push(`- **Analysis method**: 6-lens stakeholder analysis with SWOT extraction`);
  lines.push('');
 
  return lines.join('\n');
}
 
/**
 * Sanitize a document identifier for use as a safe filename.
 * Replaces non-alphanumeric characters with hyphens and lowercases.
 */
export function sanitizeDokId(dokId: string): string {
  return dokId
    .toLowerCase()
    .replace(/[^a-z0-9åäö-]/g, '-')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '')
    .slice(0, 100);
}