All files / generators breaking-content.ts

98.05% Statements 101/103
87.61% Branches 99/113
100% Functions 21/21
97.8% Lines 89/91

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                                                        8x                   66x 66x 66x           66x         8x                     83x 29x             8x                       67x 50x 50x   50x 67x   180x 180x   180x         180x 180x                   67x 67x                                 67x 17x 17x       17x             17x                                 67x 17x 17x       17x             17x                                           67x 33x 33x 33x     168x                   33x 67x 67x                                 128x 67x           67x                         6x 4x 4x     4x           4x                                 6x 2x 2x     2x           2x                                 6x 2x 2x     2x           2x                                               128x 128x 6x 6x                                             128x 39x 39x             39x                                           128x 27x 27x             27x                                                                                     128x 128x     128x                 128x                   128x   128x 128x           128x               128x 128x           128x                 128x                 128x 128x 128x   128x               128x             128x         128x                         128x                                
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/BreakingContent
 * @description Pure functions for building breaking-news article HTML.
 *
 * **Feed-first approach**: EP feed data (adopted texts, events, procedures,
 * MEP updates) is the primary news content. Analytical intelligence sections
 * (voting anomalies, coalition dynamics) are supplementary context only.
 * Precomputed statistics are NEVER the news itself.
 */
 
import { escapeHTML } from '../utils/file-utils.js';
import { getLocalizedString, EDITORIAL_STRINGS, BREAKING_STRINGS } from '../constants/languages.js';
import type { BreakingStrings } from '../types/index.js';
import type {
  VotingAnomalyIntelligence,
  CoalitionIntelligence,
  MEPInfluenceScore,
  BreakingNewsFeedData,
  AdoptedTextFeedItem,
  EventFeedItem,
  ProcedureFeedItem,
  MEPFeedItem,
} from '../types/index.js';
 
/** Maximum characters to display from raw MCP intelligence data */
const MAX_DATA_CHARS = 2000;
 
/**
 * Return true when `raw` is a JSON error object (contains an `"error"` key),
 * indicating that the MCP tool call failed rather than returning useful data.
 *
 * @param raw - Raw string from MCP tool call
 * @returns `true` when raw is a tool-error JSON payload
 */
function isToolError(raw: string): boolean {
  try {
    const parsed: unknown = JSON.parse(raw.trim());
    return (
      typeof parsed === 'object' &&
      parsed !== null &&
      'error' in (parsed as Record<string, unknown>)
    );
  } catch {
    return false;
  }
}
 
/** Maximum feed items to render per section */
const MAX_FEED_ITEMS = 10;
 
/**
 * Build a feed truncation note paragraph when displayed items are fewer than total items.
 *
 * @param shown - Number of items shown
 * @param total - Total number of items available
 * @param strings - Localized breaking strings containing `showingXofNFn`
 * @returns HTML paragraph string or empty string
 */
function buildFeedTruncationNote(shown: number, total: number, strings: BreakingStrings): string {
  if (shown >= total) return '';
  return `\n          <p class="feed-truncation-note">${escapeHTML(strings.showingXofNFn(shown, total))}</p>`;
}
 
/**
 * Regex that matches generic placeholder adopted-text titles generated by the EP feed API.
 * When matched, the label/identifier is preferred as the display title instead.
 */
const ADOPTED_TEXT_PLACEHOLDER_PATTERN = /^(Adopted text|European Parliament adopted text)/i;
 
// ─── Feed section builders ───────────────────────────────────────────────────
 
/**
 * Build adopted texts section HTML from feed items.
 *
 * @param items - Adopted text feed items
 * @param lang - Language code for localized strings
 * @returns HTML section string or empty string
 */
function buildAdoptedTextsSection(items: readonly AdoptedTextFeedItem[], lang: string): string {
  if (items.length === 0) return '';
  const strings = getLocalizedString(BREAKING_STRINGS, lang);
  const displayItems = items.slice(0, MAX_FEED_ITEMS);
  // EP API provides titles in English only — mark non-English articles accordingly
  const titleLangAttr = lang !== 'en' ? ' lang="en"' : '';
  const listItems = displayItems
    .map((item) => {
      const labelOrId = item.label ?? item.identifier;
      const titleIsPlaceholder = !item.title || ADOPTED_TEXT_PLACEHOLDER_PATTERN.test(item.title);
      const displayTitle =
        (titleIsPlaceholder
          ? labelOrId
            ? strings.adoptedTextItemLabelFn(labelOrId)
            : item.title
          : item.title) ?? '';
      const showSecondaryLabel = !titleIsPlaceholder && labelOrId;
      return (
        `<li class="feed-item adopted-text-item">` +
        `<strong${titleLangAttr}>${escapeHTML(displayTitle)}</strong>` +
        `${showSecondaryLabel && labelOrId ? ` <span class="feed-label">${escapeHTML(labelOrId)}</span>` : ''}` +
        `${item.date ? ` <span class="feed-date">(${escapeHTML(item.date)})</span>` : ''}` +
        `${item.type ? ` <span class="feed-type">${escapeHTML(strings.adoptedTextTypeLabel)}</span>` : ''}` +
        `</li>`
      );
    })
    .join('\n            ');
  const truncationNote = buildFeedTruncationNote(displayItems.length, items.length, strings);
  return `
        <section class="adopted-texts-feed">
          <h2>${escapeHTML(strings.adoptedTextsHeading)}</h2>
          <ul>
            ${listItems}
          </ul>${truncationNote}
        </section>`;
}
 
/**
 * Build recent events section HTML from feed items.
 *
 * @param items - Event feed items
 * @param lang - Language code for localized strings
 * @returns HTML section string or empty string
 */
function buildRecentEventsSection(items: readonly EventFeedItem[], lang: string): string {
  if (items.length === 0) return '';
  const strings = getLocalizedString(BREAKING_STRINGS, lang);
  const listItems = items
    .slice(0, MAX_FEED_ITEMS)
    .map(
      (item) =>
        `<li class="feed-item event-item">` +
        `<strong>${escapeHTML(item.title)}</strong>` +
        `${item.date ? ` <span class="feed-date">(${escapeHTML(item.date)})</span>` : ''}` +
        `${item.location ? ` <span class="feed-location">${escapeHTML(item.location)}</span>` : ''}` +
        `</li>`
    )
    .join('\n            ');
  return `
        <section class="events-feed">
          <h2>${escapeHTML(strings.recentEventsHeading)}</h2>
          <ul>
            ${listItems}
          </ul>
        </section>`;
}
 
/**
 * Build procedure updates section HTML from feed items.
 *
 * @param items - Procedure feed items
 * @param lang - Language code for localized strings
 * @returns HTML section string or empty string
 */
function buildProcedureUpdatesSection(items: readonly ProcedureFeedItem[], lang: string): string {
  if (items.length === 0) return '';
  const strings = getLocalizedString(BREAKING_STRINGS, lang);
  const listItems = items
    .slice(0, MAX_FEED_ITEMS)
    .map(
      (item) =>
        `<li class="feed-item procedure-item">` +
        `<strong>${escapeHTML(item.title)}</strong>` +
        `${item.stage ? ` <span class="feed-stage">[${escapeHTML(item.stage)}]</span>` : ''}` +
        `${item.date ? ` <span class="feed-date">(${escapeHTML(item.date)})</span>` : ''}` +
        `</li>`
    )
    .join('\n            ');
  return `
        <section class="procedures-feed">
          <h2>${escapeHTML(strings.procedureUpdatesHeading)}</h2>
          <ul>
            ${listItems}
          </ul>
        </section>`;
}
 
/**
 * Build MEP updates section HTML from feed items.
 *
 * @param items - MEP feed items (up to the fetch limit)
 * @param lang - Language code for localized strings
 * @param totalCount - Optional total MEP updates reported by the feed API (may exceed fetched items)
 * @returns HTML section string or empty string
 */
function buildMEPUpdatesSection(
  items: readonly MEPFeedItem[],
  lang: string,
  totalCount?: number
): string {
  if (items.length === 0) return '';
  const strings = getLocalizedString(BREAKING_STRINGS, lang);
  const displayItems = items.slice(0, MAX_FEED_ITEMS);
  const listItems = displayItems
    .map(
      (item) =>
        `<li class="feed-item mep-item">` +
        `<strong>${escapeHTML(item.name)}</strong>` +
        `${item.date ? ` <span class="feed-date">(${escapeHTML(item.date)})</span>` : ''}` +
        `${item.country ? ` <span class="feed-country">(${escapeHTML(item.country)})</span>` : ''}` +
        `${item.group ? ` <span class="feed-group">${escapeHTML(item.group)}</span>` : ''}` +
        `</li>`
    )
    .join('\n            ');
  // Use API total count when available and larger than fetched count; otherwise fall back to fetched count
  const reportedTotal =
    totalCount !== undefined && totalCount > items.length ? totalCount : items.length;
  const truncationNote = buildFeedTruncationNote(displayItems.length, reportedTotal, strings);
  return `
        <section class="mep-updates-feed">
          <h2>${escapeHTML(strings.mepUpdatesHeading)}</h2>
          <ul>
            ${listItems}
          </ul>${truncationNote}
        </section>`;
}
 
/**
 * Build the combined feed-based news sections (primary content).
 *
 * @param feedData - Aggregated feed data
 * @param lang - Language code
 * @returns HTML string with all feed sections
 */
function buildFeedSections(feedData: BreakingNewsFeedData | undefined, lang: string): string {
  if (!feedData) return '';
  const sections = [
    buildAdoptedTextsSection(feedData.adoptedTexts, lang),
    buildRecentEventsSection(feedData.events, lang),
    buildProcedureUpdatesSection(feedData.procedures, lang),
    buildMEPUpdatesSection(feedData.mepUpdates, lang, feedData.totalMEPUpdates),
  ];
  return sections.filter(Boolean).join('');
}
 
// ─── Private intelligence section builders ───────────────────────────────────
 
/**
 * Build intelligence briefing section HTML from structured anomaly data
 *
 * @param anomalies - Structured voting anomaly intelligence items
 * @param lang - Language code for localized strings
 * @returns HTML section string or empty string
 */
function buildAnomalyAlertSection(anomalies: VotingAnomalyIntelligence[], lang: string): string {
  if (anomalies.length === 0) return '';
  const strings = getLocalizedString(BREAKING_STRINGS, lang);
  const items = anomalies
    .map(
      (a) =>
        `<li class="anomaly-${escapeHTML(a.significance)}">` +
        `<strong>${escapeHTML(a.description)}</strong> — ` +
        `${escapeHTML(a.implication)} ` +
        `(deviation: ${escapeHTML(String(a.deviationPercentage))}%)</li>`
    )
    .join('\n            ');
  return `
        <section class="anomaly-alert">
          <h3>${escapeHTML(strings.votingAnomalyAlert)}</h3>
          <ul>
            ${items}
          </ul>
        </section>`;
}
 
/**
 * Build coalition dynamics section HTML from structured coalition data
 *
 * @param coalitions - Structured coalition intelligence items
 * @param lang - Language code for localized strings
 * @returns HTML section string or empty string
 */
function buildCoalitionDynamicsSection(coalitions: CoalitionIntelligence[], lang: string): string {
  if (coalitions.length === 0) return '';
  const strings = getLocalizedString(BREAKING_STRINGS, lang);
  const items = coalitions
    .map(
      (c) =>
        `<li class="coalition-${escapeHTML(c.riskLevel)}">` +
        `${escapeHTML(c.groups.join(', '))} — ` +
        `cohesion: ${escapeHTML(String(Math.round(c.cohesionScore * 100)))}% ` +
        `(${escapeHTML(c.alignmentTrend)})</li>`
    )
    .join('\n            ');
  return `
        <section class="coalition-dynamics">
          <h3>${escapeHTML(strings.coalitionDynamicsSection)}</h3>
          <ul>
            ${items}
          </ul>
        </section>`;
}
 
/**
 * Build key parliamentary players section HTML from structured MEP influence data
 *
 * @param mepScores - Structured MEP influence score items
 * @param lang - Language code for localized strings
 * @returns HTML section string or empty string
 */
function buildKeyPlayersIntelSection(mepScores: MEPInfluenceScore[], lang: string): string {
  if (mepScores.length === 0) return '';
  const strings = getLocalizedString(BREAKING_STRINGS, lang);
  const items = mepScores
    .map(
      (m) =>
        `<li class="mep-score">` +
        `<strong>${escapeHTML(m.mepName)}</strong> — ` +
        `score: ${escapeHTML(String(Math.round(m.overallScore)))} ` +
        `${m.rank ? `(${escapeHTML(m.rank)})` : ''}</li>`
    )
    .join('\n            ');
  return `
        <section class="key-players-intel">
          <h3>${escapeHTML(strings.keyPlayers)}</h3>
          <ul>
            ${items}
          </ul>
        </section>`;
}
 
/**
 * Build intelligence briefing section HTML from all structured sources
 *
 * @param anomalies - Structured voting anomaly intelligence items
 * @param coalitions - Structured coalition intelligence items
 * @param mepScores - Structured MEP influence score items
 * @param lang - Language code for localized strings
 * @returns HTML section string or empty string
 */
function buildIntelligenceBriefingSection(
  anomalies: VotingAnomalyIntelligence[],
  coalitions: CoalitionIntelligence[],
  mepScores: MEPInfluenceScore[],
  lang: string
): string {
  const hasIntel = anomalies.length > 0 || coalitions.length > 0 || mepScores.length > 0;
  if (!hasIntel) return '';
  const strings = getLocalizedString(BREAKING_STRINGS, lang);
  return `
        <section class="intelligence-briefing">
          <h2>${escapeHTML(strings.intelligenceBriefing)}</h2>
          ${buildAnomalyAlertSection(anomalies, lang)}
          ${buildCoalitionDynamicsSection(coalitions, lang)}
          ${buildKeyPlayersIntelSection(mepScores, lang)}
        </section>`;
}
 
/**
 * Build voting anomaly section HTML, showing a localized fallback when the raw
 * data is a tool-error payload rather than useful intelligence.
 *
 * @param raw - Raw anomaly data string from MCP (may be empty or an error JSON)
 * @param strings - Localized breaking-news strings for the target language
 * @param sourceAttribution - Localized source attribution label
 * @returns HTML section string or empty string
 */
function buildAnomalyRawSection(
  raw: string,
  strings: BreakingStrings,
  sourceAttribution: string
): string {
  if (!raw) return '';
  const heading = `<h2>${escapeHTML(strings.votingAnomalyIntel)}</h2>`;
  Iif (isToolError(raw)) {
    return `
        <section class="analysis">
          ${heading}
          <p class="data-narrative">${escapeHTML(strings.anomalyUnavailable)}</p>
        </section>`;
  }
  return `
        <section class="analysis">
          ${heading}
          <p class="source-attribution">${escapeHTML(sourceAttribution)}:</p>
          <p class="data-narrative">${escapeHTML(raw.slice(0, MAX_DATA_CHARS))}</p>
        </section>`;
}
 
/**
 * Build coalition dynamics section HTML, showing a localized fallback when the
 * raw data is a tool-error payload rather than useful intelligence.
 *
 * @param raw - Raw coalition data string from MCP (may be empty or an error JSON)
 * @param strings - Localized breaking-news strings for the target language
 * @param sourceAttribution - Localized source attribution label
 * @returns HTML section string or empty string
 */
function buildCoalitionRawSection(
  raw: string,
  strings: BreakingStrings,
  sourceAttribution: string
): string {
  if (!raw) return '';
  const heading = `<h2>${escapeHTML(strings.coalitionDynamics)}</h2>`;
  Iif (isToolError(raw)) {
    return `
        <section class="coalition-impact">
          ${heading}
          <p class="data-narrative">${escapeHTML(strings.coalitionUnavailable)}</p>
        </section>`;
  }
  return `
        <section class="coalition-impact">
          ${heading}
          <p class="source-attribution">${escapeHTML(sourceAttribution)}:</p>
          <p class="data-narrative">${escapeHTML(raw.slice(0, MAX_DATA_CHARS))}</p>
        </section>`;
}
 
// ─── Exported function ────────────────────────────────────────────────────────
 
/**
 * Build breaking news article HTML content.
 *
 * **Feed-first**: When `feedData` is provided, feed sections are the primary
 * content and appear first. Raw MCP analytical data and structured intelligence
 * sections are rendered as supplementary context below.
 *
 * When no data is provided at all, returns a placeholder notice.
 *
 * @param date - Current date string for the article
 * @param anomalyRaw - Raw anomaly data from MCP (context only)
 * @param coalitionRaw - Raw coalition dynamics data from MCP (context only)
 * @param reportRaw - Raw analytical report from MCP (context only)
 * @param influenceRaw - Raw MEP influence data from MCP (context only)
 * @param lang - Language code for localized editorial strings (default: 'en')
 * @param anomalies - Optional structured voting anomaly intelligence items
 * @param coalitions - Optional structured coalition intelligence items
 * @param mepScores - Optional structured MEP influence score items
 * @param feedData - Optional EP feed data (adopted texts, events, procedures, MEPs)
 * @returns Full article HTML content string
 */
export function buildBreakingNewsContent(
  date: string,
  anomalyRaw: string,
  coalitionRaw: string,
  reportRaw: string,
  influenceRaw: string,
  lang = 'en',
  anomalies: VotingAnomalyIntelligence[] = [],
  coalitions: CoalitionIntelligence[] = [],
  mepScores: MEPInfluenceScore[] = [],
  feedData?: BreakingNewsFeedData
): string {
  const editorial = getLocalizedString(EDITORIAL_STRINGS, lang);
  const strings = getLocalizedString(BREAKING_STRINGS, lang);
 
  // Feed data is the primary news content
  const hasFeedData = Boolean(
    feedData &&
    (feedData.adoptedTexts.length > 0 ||
      feedData.events.length > 0 ||
      feedData.procedures.length > 0 ||
      feedData.mepUpdates.length > 0)
  );
 
  // Analytical data is context only
  const hasAnalyticalData = Boolean(
    anomalyRaw ||
    coalitionRaw ||
    reportRaw ||
    influenceRaw ||
    anomalies.length ||
    coalitions.length ||
    mepScores.length
  );
 
  const hasData = hasFeedData || hasAnalyticalData;
  // MCP is truly unavailable only when feedData is undefined AND no analytical data
  const isMCPUnavailable = !feedData && !hasAnalyticalData;
  const timestamp = new Date().toISOString();
 
  // ─── Feed sections (PRIMARY news content) ──────────────────────────────
  // When feedData is present but empty AND hasAnalyticalData is false,
  // the lede already conveys noFeedDataNotice — skip the duplicate section.
  const feedSections =
    feedData && !hasFeedData && hasAnalyticalData
      ? `
        <section class="feed-empty-notice">
          <p>${escapeHTML(strings.noFeedDataNotice)}</p>
        </section>`
      : buildFeedSections(feedData, lang);
 
  // ─── Analytical context sections (SECONDARY) ──────────────────────────
  const anomalySection = buildAnomalyRawSection(anomalyRaw, strings, editorial.sourceAttribution);
  const coalitionSection = buildCoalitionRawSection(
    coalitionRaw,
    strings,
    editorial.sourceAttribution
  );
 
  const reportSection = reportRaw
    ? `
        <section class="context">
          <h2>${escapeHTML(strings.analyticalReport)}</h2>
          <p class="source-attribution">${escapeHTML(editorial.analysisNote)}:</p>
          <p class="data-narrative">${escapeHTML(reportRaw.slice(0, MAX_DATA_CHARS))}</p>
        </section>`
    : '';
 
  const keyPlayersSection = influenceRaw
    ? `
        <section class="key-players">
          <h2>${escapeHTML(strings.keyMEPInfluence)}</h2>
          <p class="source-attribution">${escapeHTML(editorial.sourceAttribution)}:</p>
          <p class="data-narrative">${escapeHTML(influenceRaw.slice(0, MAX_DATA_CHARS))}</p>
        </section>`
    : '';
 
  const context = escapeHTML(editorial.parliamentaryContext);
  const finding = escapeHTML(editorial.keyTakeaway);
  const attribution = escapeHTML(editorial.sourceAttribution);
 
  const whyThisMattersSection = hasData
    ? `
        <section class="why-this-matters">
          <h2>${escapeHTML(editorial.whyThisMatters)}</h2>
          <p>${context}: ${finding} — ${attribution}.</p>
        </section>`
    : '';
 
  const intelligenceBriefing = buildIntelligenceBriefingSection(
    anomalies,
    coalitions,
    mepScores,
    lang
  );
 
  const ledeText = hasAnalyticalData
    ? strings.lede
    : hasFeedData
      ? strings.feedLede
      : strings.noFeedDataNotice;
  const placeholderNotice = isMCPUnavailable
    ? `
        <div class="notice">
          <p><strong>Note:</strong> ${escapeHTML(strings.placeholderNotice)}</p>
        </div>
        <section class="lede">
          <p>${escapeHTML(strings.placeholderLede)}</p>
        </section>`
    : `
        <section class="lede">
          <p>${escapeHTML(ledeText.replace(/[.。]$/, '').trimEnd())} ${escapeHTML(strings.asOf)} ${escapeHTML(date)}.</p>
        </section>`;
 
  return `
        <div class="article-content">
          <section class="breaking-banner">
            <p class="breaking-timestamp">${escapeHTML(strings.breakingBanner)} — ${escapeHTML(timestamp)}</p>
          </section>
          ${placeholderNotice}
          ${feedSections}
          ${intelligenceBriefing}
          ${anomalySection}
          ${coalitionSection}
          ${reportSection}
          ${keyPlayersSection}
          ${whyThisMattersSection}
        </div>
      `;
}