All files / generators week-ahead-content.ts

92.17% Statements 106/115
83.55% Branches 127/152
90.62% Functions 29/32
92.39% Lines 85/92

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                                                        8x     8x                                                   8x 7x 7x 8x     8x 4x             1x                             8x 7x 7x 8x                 8x 4x             1x                             6x 5x 5x 6x                     6x 3x                                                     5x 4x 4x 5x                     5x 2x                                             5x 4x 4x 5x                   5x 2x                                           1x 1x 1x 1x                   1x                                             13x                                     21x     21x                                   18x                               20x                               18x                                   56x   23x       56x     56x 56x                               56x 56x   56x         56x               56x               56x               56x             56x   56x           56x                                                   10x 10x 3x 2x     10x 10x 10x           8x     8x     8x     8x                 8x 8x     4x                         8x 9x     5x                         8x 8x       4x                                         15x   8x     8x 7x 7x                
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/WeekAheadContent
 * @description Pure functions for parsing MCP data and building week-ahead article HTML.
 * No side effects — all functions accept data and return strings.
 */
 
import { escapeHTML } from '../utils/file-utils.js';
import {
  getLocalizedString,
  EDITORIAL_STRINGS,
  WEEK_AHEAD_STRINGS,
} from '../constants/languages.js';
import type {
  ParliamentEvent,
  CommitteeMeeting,
  LegislativeDocument,
  LegislativeProcedure,
  ParliamentaryQuestion,
  WeekAheadData,
  DateRange,
  MCPToolResult,
  LegislativeVelocity,
} from '../types/index.js';
 
/** Keyword constant for article tagging */
const KEYWORD_EUROPEAN_PARLIAMENT = 'European Parliament';
 
/** Placeholder events used when MCP is unavailable or returns no sessions */
export const PLACEHOLDER_EVENTS: ParliamentEvent[] = [
  {
    date: '',
    title: 'Plenary Session',
    type: 'Plenary',
    description: 'Full parliamentary session',
  },
  {
    date: '',
    title: 'ENVI Committee Meeting',
    type: 'Committee',
    description: 'Environment committee discussion',
  },
];
 
/**
 * Parse plenary sessions from a settled MCP result
 *
 * @param settled - Promise.allSettled result
 * @param fallbackDate - Fallback date when session has none
 * @returns Array of parliament events
 */
export function parsePlenarySessions(
  settled: PromiseSettledResult<MCPToolResult>,
  fallbackDate: string
): ParliamentEvent[] {
  if (settled.status !== 'fulfilled') return [];
  try {
    const text = settled.value.content?.[0]?.text ?? '{}';
    const data = JSON.parse(text) as {
      sessions?: Array<{ date?: string; title?: string; type?: string; description?: string }>;
    };
    if (!data.sessions || data.sessions.length === 0) return [];
    return data.sessions.map((s) => ({
      date: s.date ?? fallbackDate,
      title: s.title ?? 'Parliamentary Session',
      type: s.type ?? 'Session',
      description: s.description ?? '',
    }));
  } catch {
    return [];
  }
}
 
/**
 * Parse EP events (hearings, conferences, seminars) from a settled MCP result
 *
 * @param settled - Promise.allSettled result
 * @param fallbackDate - Fallback date when event has none
 * @returns Array of parliament events
 */
export function parseEPEvents(
  settled: PromiseSettledResult<MCPToolResult>,
  fallbackDate: string
): ParliamentEvent[] {
  if (settled.status !== 'fulfilled') return [];
  try {
    const text = settled.value.content?.[0]?.text ?? '{}';
    const data = JSON.parse(text) as {
      events?: Array<{
        date?: string;
        title?: string;
        type?: string;
        description?: string;
        location?: string;
      }>;
    };
    if (!data.events || data.events.length === 0) return [];
    return data.events.map((e) => ({
      date: e.date ?? fallbackDate,
      title: e.title ?? 'EP Event',
      type: e.type ?? 'Event',
      description: e.description ?? '',
    }));
  } catch {
    return [];
  }
}
 
/**
 * Parse committee meetings from a settled MCP result
 *
 * @param settled - Promise.allSettled result
 * @param fallbackDate - Fallback date when meeting has no date
 * @returns Array of committee meetings
 */
export function parseCommitteeMeetings(
  settled: PromiseSettledResult<MCPToolResult>,
  fallbackDate?: string
): CommitteeMeeting[] {
  if (settled.status !== 'fulfilled') return [];
  try {
    const text = settled.value.content?.[0]?.text ?? '{}';
    const data = JSON.parse(text) as {
      committees?: Array<{
        id?: string;
        committee?: string;
        committeeName?: string;
        date?: string;
        time?: string;
        location?: string;
        agenda?: Array<{ item?: number; title?: string; type?: string }>;
      }>;
    };
    if (!data.committees || data.committees.length === 0) return [];
    return data.committees.map((c) => ({
      id: c.id,
      committee: c.committee ?? 'Unknown',
      committeeName: c.committeeName,
      date: c.date ?? fallbackDate ?? '',
      time: c.time,
      location: c.location,
      agenda: c.agenda?.map((a) => ({
        item: a.item,
        title: a.title ?? '',
        type: a.type,
      })),
    }));
  } catch {
    return [];
  }
}
 
/**
 * Parse legislative documents from a settled MCP result
 *
 * @param settled - Promise.allSettled result
 * @returns Array of legislative documents
 */
export function parseLegislativeDocuments(
  settled: PromiseSettledResult<MCPToolResult>
): LegislativeDocument[] {
  if (settled.status !== 'fulfilled') return [];
  try {
    const text = settled.value.content?.[0]?.text ?? '{}';
    const data = JSON.parse(text) as {
      documents?: Array<{
        id?: string;
        type?: string;
        title?: string;
        date?: string;
        status?: string;
        committee?: string;
        rapporteur?: string;
      }>;
    };
    if (!data.documents || data.documents.length === 0) return [];
    return data.documents.map((d) => ({
      id: d.id,
      type: d.type,
      title: d.title ?? 'Untitled Document',
      date: d.date,
      status: d.status,
      committee: d.committee,
      rapporteur: d.rapporteur,
    }));
  } catch {
    return [];
  }
}
 
/**
 * Parse legislative pipeline from a settled MCP result
 *
 * @param settled - Promise.allSettled result
 * @returns Array of legislative procedures
 */
export function parseLegislativePipeline(
  settled: PromiseSettledResult<MCPToolResult>
): LegislativeProcedure[] {
  if (settled.status !== 'fulfilled') return [];
  try {
    const text = settled.value.content?.[0]?.text ?? '{}';
    const data = JSON.parse(text) as {
      procedures?: Array<{
        id?: string;
        title?: string;
        stage?: string;
        committee?: string;
        status?: string;
        bottleneck?: boolean;
      }>;
    };
    if (!data.procedures || data.procedures.length === 0) return [];
    return data.procedures.map((p) => ({
      id: p.id,
      title: p.title ?? 'Unnamed Procedure',
      stage: p.stage,
      committee: p.committee,
      status: p.status,
      bottleneck: p.bottleneck,
    }));
  } catch {
    return [];
  }
}
 
/**
 * Parse parliamentary questions from a settled MCP result
 *
 * @param settled - Promise.allSettled result
 * @returns Array of parliamentary questions
 */
export function parseParliamentaryQuestions(
  settled: PromiseSettledResult<MCPToolResult>
): ParliamentaryQuestion[] {
  Iif (settled.status !== 'fulfilled') return [];
  try {
    const text = settled.value.content?.[0]?.text ?? '{}';
    const data = JSON.parse(text) as {
      questions?: Array<{
        id?: string;
        type?: string;
        author?: string;
        subject?: string;
        date?: string;
        status?: string;
      }>;
    };
    Eif (!data.questions || data.questions.length === 0) return [];
    return data.questions.map((q) => ({
      id: q.id,
      type: q.type,
      author: q.author,
      subject: q.subject ?? 'No subject',
      date: q.date,
      status: q.status,
    }));
  } catch {
    return [];
  }
}
 
// ─── Render helpers ──────────────────────────────────────────────────────────
 
/**
 * Render a single plenary event as HTML
 *
 * @param event - Parliament event data
 * @returns HTML string
 */
function renderPlenaryEvent(event: ParliamentEvent): string {
  return `
              <div class="event-item">
                <div class="event-date">${escapeHTML(event.date)}</div>
                <div class="event-details">
                  <h3>${escapeHTML(event.title)}</h3>
                  <p class="event-type">${escapeHTML(event.type)}</p>
                  ${event.description ? `<p>${escapeHTML(event.description)}</p>` : ''}
                </div>
              </div>`;
}
 
/**
 * Render a single committee meeting as HTML
 *
 * @param meeting - Committee meeting data
 * @returns HTML string
 */
function renderCommitteeMeeting(meeting: CommitteeMeeting): string {
  const agendaHtml =
    meeting.agenda && meeting.agenda.length > 0
      ? `<ul class="agenda-list">${meeting.agenda.map((item) => `<li>${escapeHTML(item.title)}${item.type ? ` <span class="agenda-type">(${escapeHTML(item.type)})</span>` : ''}</li>`).join('')}</ul>`
      : '';
  return `
              <div class="committee-item">
                <div class="committee-date">${escapeHTML(meeting.date)}${meeting.time ? ` ${escapeHTML(meeting.time)}` : ''}</div>
                <div class="committee-details">
                  <h3>${escapeHTML(meeting.committeeName ?? meeting.committee)}</h3>
                  ${meeting.location ? `<p class="committee-location">${escapeHTML(meeting.location)}</p>` : ''}
                  ${agendaHtml}
                </div>
              </div>`;
}
 
/**
 * Render a single legislative document as HTML
 *
 * @param doc - Legislative document
 * @returns HTML string
 */
function renderLegislativeDocument(doc: LegislativeDocument): string {
  return `
              <li class="document-item">
                <span class="document-title">${escapeHTML(doc.title)}</span>
                ${doc.type ? ` <span class="document-type">(${escapeHTML(doc.type)})</span>` : ''}
                ${doc.committee ? ` — <span class="document-committee">${escapeHTML(doc.committee)}</span>` : ''}
                ${doc.status ? ` <span class="document-status">[${escapeHTML(doc.status)}]</span>` : ''}
              </li>`;
}
 
/**
 * Render a single pipeline procedure as HTML
 *
 * @param proc - Legislative procedure
 * @returns HTML string
 */
function renderPipelineProcedure(proc: LegislativeProcedure): string {
  return `
              <li class="pipeline-item${proc.bottleneck ? ' bottleneck' : ''}">
                <span class="procedure-title">${escapeHTML(proc.title)}</span>
                ${proc.stage ? ` <span class="procedure-stage">${escapeHTML(proc.stage)}</span>` : ''}
                ${proc.committee ? ` — <span class="procedure-committee">${escapeHTML(proc.committee)}</span>` : ''}
                ${proc.bottleneck ? ' <span class="bottleneck-indicator">⚠ Bottleneck</span>' : ''}
              </li>`;
}
 
/**
 * Render a single parliamentary question as HTML
 *
 * @param q - Parliamentary question
 * @returns HTML string
 */
function renderQuestion(q: ParliamentaryQuestion): string {
  return `
              <li class="qa-item">
                <span class="qa-subject">${escapeHTML(q.subject)}</span>
                ${q.type ? ` <span class="qa-type">(${escapeHTML(q.type)})</span>` : ''}
                ${q.author ? ` — <span class="qa-author">${escapeHTML(q.author)}</span>` : ''}
              </li>`;
}
 
// ─── Content builders ────────────────────────────────────────────────────────
 
/**
 * Build the supplementary lede sentence about committee and pipeline counts.
 *
 * @param committeeCount - Number of committee meetings
 * @param pipelineCount - Number of pipeline procedures
 * @returns Sentence fragment or empty string
 */
function buildLedeDetail(committeeCount: number, pipelineCount: number): string {
  if (committeeCount === 0 && pipelineCount === 0) return '';
  const committeePart =
    committeeCount > 0
      ? `${committeeCount} committee meeting${committeeCount !== 1 ? 's are' : ' is'} scheduled`
      : '';
  const pipelinePart =
    pipelineCount > 0
      ? `${pipelineCount} legislative procedure${pipelineCount !== 1 ? 's are' : ' is'} advancing through the pipeline`
      : '';
  const conjunction = committeePart && pipelinePart ? ' and ' : '';
  return ` Notably, ${committeePart}${conjunction}${pipelinePart}.`;
}
 
/**
 * Build article content HTML from week-ahead data
 *
 * @param weekData - Aggregated week-ahead data
 * @param dateRange - Date range for the article
 * @param lang - Language code for editorial strings (default: 'en')
 * @returns HTML content string
 */
export function buildWeekAheadContent(
  weekData: WeekAheadData,
  dateRange: DateRange,
  lang = 'en'
): string {
  const editorial = getLocalizedString(EDITORIAL_STRINGS, lang);
  const strings = getLocalizedString(WEEK_AHEAD_STRINGS, lang);
  const plenaryHtml =
    weekData.events.length > 0
      ? weekData.events.map(renderPlenaryEvent).join('')
      : `<p>${escapeHTML(strings.noPlenary)}</p>`;
 
  const committeeSection =
    weekData.committees.length > 0
      ? `<section class="committee-calendar">
            <h2>${escapeHTML(strings.committeeMeetings)}</h2>
            ${weekData.committees.map(renderCommitteeMeeting).join('')}
          </section>`
      : '';
 
  const documentsSection =
    weekData.documents.length > 0
      ? `<section class="legislative-documents">
            <h2>${escapeHTML(strings.legislativeDocuments)}</h2>
            <ul class="document-list">${weekData.documents.map(renderLegislativeDocument).join('')}</ul>
          </section>`
      : '';
 
  const pipelineSection =
    weekData.pipeline.length > 0
      ? `<section class="legislative-pipeline">
            <h2>${escapeHTML(strings.legislativePipeline)}</h2>
            <ul class="pipeline-list">${weekData.pipeline.map(renderPipelineProcedure).join('')}</ul>
          </section>`
      : '';
 
  const qaSection =
    weekData.questions.length > 0
      ? `<section class="qa-schedule">
            <h2>${escapeHTML(strings.parliamentaryQuestions)}</h2>
            <ul class="qa-list">${weekData.questions.map(renderQuestion).join('')}</ul>
          </section>`
      : '';
 
  const ledeDetail = buildLedeDetail(weekData.committees.length, weekData.pipeline.length);
 
  const whyThisMattersSection = `
          <section class="why-this-matters">
            <h2>${escapeHTML(editorial.whyThisMatters)}</h2>
            <p>${escapeHTML(editorial.parliamentaryContext)}: ${escapeHTML(editorial.sourceAttribution)} — parliamentary schedules determine the legislative agenda affecting EU citizens directly.</p>
          </section>`;
 
  return `
        <div class="article-content">
          <section class="lede">
            <p>${escapeHTML(strings.lede)} from ${escapeHTML(dateRange.start)} to ${escapeHTML(dateRange.end)}.${escapeHTML(ledeDetail)}</p>
          </section>
          ${whyThisMattersSection}
          <section class="plenary-schedule">
            <h2>${escapeHTML(strings.plenarySessions)}</h2>
            ${plenaryHtml}
          </section>
          ${committeeSection}
          ${documentsSection}
          ${pipelineSection}
          ${qaSection}
          <!-- /article-content -->
        </div>
      `;
}
 
/**
 * Build article keywords from week-ahead data
 *
 * @param weekData - Aggregated week-ahead data
 * @returns Array of keyword strings
 */
export function buildKeywords(weekData: WeekAheadData): string[] {
  const keywords = [KEYWORD_EUROPEAN_PARLIAMENT, 'week ahead', 'plenary', 'committees'];
  for (const c of weekData.committees) {
    if (c.committee && !keywords.includes(c.committee)) {
      keywords.push(c.committee);
    }
  }
  if (weekData.pipeline.length > 0) keywords.push('legislative pipeline');
  if (weekData.questions.length > 0) keywords.push('parliamentary questions');
  return keywords;
}
 
// ─── What-to-Watch section ─────────────────────────────────────────────────
 
/** CSS class for bottleneck-risk watch items */
const CSS_WATCH_HIGH = 'watch-high';
 
/** CSS class for bottlenecked procedure watch items */
const CSS_WATCH_PROCEDURE = 'watch-procedure';
 
/** CSS class for standard velocity watch items */
const CSS_WATCH_ITEM = 'watch-item';
 
/** Maximum number of non-bottleneck velocity items to include */
const WATCH_MAX_NORMAL_ITEMS = 3;
 
/**
 * Build list items for high-risk velocities
 *
 * @param velocities - All legislative velocities
 * @returns HTML list items for high bottleneck risk items
 */
function buildHighRiskItems(velocities: LegislativeVelocity[]): string {
  return velocities
    .filter((v) => v.bottleneckRisk === 'high')
    .map(
      (v) =>
        `<li class="${CSS_WATCH_HIGH}">${escapeHTML(v.title)} — ` +
        `Stage: ${escapeHTML(v.stage)} (bottleneck risk detected)</li>`
    )
    .join('');
}
 
/**
 * Build list items for procedures flagged as bottlenecks
 *
 * @param procedures - All legislative procedures
 * @returns HTML list items for bottlenecked procedures
 */
function buildBottleneckProcedureItems(procedures: LegislativeProcedure[]): string {
  return procedures
    .filter((p) => p.bottleneck === true)
    .map(
      (p) =>
        `<li class="${CSS_WATCH_PROCEDURE}">${escapeHTML(p.title)} — ` +
        `${escapeHTML(p.stage ?? 'in progress')} stage</li>`
    )
    .join('');
}
 
/**
 * Build list items for normal-risk velocities
 *
 * @param velocities - All legislative velocities
 * @returns HTML list items for the top normal-risk velocity items
 */
function buildNormalVelocityItems(velocities: LegislativeVelocity[]): string {
  return velocities
    .filter((v) => v.bottleneckRisk !== 'high')
    .slice(0, WATCH_MAX_NORMAL_ITEMS)
    .map(
      (v) =>
        `<li class="${CSS_WATCH_ITEM}">${escapeHTML(v.title)} — ` +
        `predicted completion: ${escapeHTML(v.predictedCompletion)}</li>`
    )
    .join('');
}
 
/**
 * Build predictive "What to Watch" analysis section showing legislative
 * procedures and velocity data ordered by bottleneck risk.
 * Returns an empty string when both input arrays are empty or yield no items.
 *
 * @param procedures - Legislative procedures to analyse
 * @param velocities - Legislative velocity data (for example from a separate velocity analysis feed)
 * @param language - BCP 47 language code used as the section lang attribute
 * @returns HTML string for the "What to Watch" section
 */
export function buildWhatToWatchSection(
  procedures: LegislativeProcedure[],
  velocities: LegislativeVelocity[],
  language: string
): string {
  if (procedures.length === 0 && velocities.length === 0) return '';
  const allItems =
    buildHighRiskItems(velocities) +
    buildBottleneckProcedureItems(procedures) +
    buildNormalVelocityItems(velocities);
  if (!allItems) return '';
  const strings = getLocalizedString(WEEK_AHEAD_STRINGS, language);
  return `
        <section class="what-to-watch" lang="${escapeHTML(language)}">
          <h2>${escapeHTML(strings.whatToWatch)}</h2>
          <ul>
            ${allItems}
          </ul>
        </section>`;
}