All files / src/generators/strategies propositions-strategy.ts

98.97% Statements 97/98
81.81% Branches 72/88
100% Functions 7/7
98.88% Lines 89/90

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                                                                                    8x                                   13x   13x 1x 1x     13x 1x 1x     13x 12x 12x     13x                     8x   8x 8x   8x 8x   8x 8x 8x 8x 7x 7x     8x 1x     7x 7x                   8x 8x 8x 8x 8x 8x 6x 6x   8x                             5x 5x   5x 5x                     5x 1x                   5x                                                           26x   26x                                     9x   9x 2x       9x             9x       9x 9x   9x       9x 9x 9x 5x 5x 5x     5x 5x 5x       9x 4x     9x                                   9x 9x               9x             9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x                           13x 13x 13x 13x 13x 13x 13x                     8x  
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/Strategies/PropositionsStrategy
 * @description Article strategy for the Propositions article type.
 * Fetches legislative proposals and active pipeline data from MCP, then
 * renders a language-specific legislative overview article.
 */
 
import type { EuropeanParliamentMCPClient } from '../../mcp/ep-mcp-client.js';
import { ArticleCategory } from '../../types/index.js';
import type { LanguageCode, EPFeedData } from '../../types/index.js';
import { escapeHTML } from '../../utils/file-utils.js';
import {
  PROPOSITIONS_TITLES,
  PROPOSITIONS_STRINGS,
  getLocalizedString,
} from '../../constants/languages.js';
import {
  computeRollingDateRange,
  fetchProposalsFromMCP,
  fetchPipelineFromMCP,
  fetchProcedureStatusFromMCP,
  fetchEPFeedData,
} from '../pipeline/fetch-stage.js';
import { buildPropositionsContent } from '../propositions-content.js';
import { buildDeepAnalysisSection } from '../deep-analysis-content.js';
import {
  buildPropositionsAnalysis,
  buildPropositionsSwot,
  buildPropositionsDashboard,
  buildPropositionsMindmap,
} from '../analysis-builders.js';
import { buildSwotSection } from '../swot-content.js';
import { buildDashboardSection } from '../dashboard-content.js';
import { buildIntelligenceMindmapSection } from '../mindmap-content.js';
import type { PipelineData } from '../propositions-content.js';
import type { ArticleStrategy, ArticleData, ArticleMetadata } from './article-strategy.js';
import { pl } from '../../utils/metadata-utils.js';
 
/** Base keywords shared by all Propositions articles */
const PROPOSITIONS_BASE_KEYWORDS = [
  'European Parliament',
  'legislation',
  'proposals',
  'procedure',
  'OLP',
] as const;
 
/**
 * Extract content-aware keywords from propositions data and feed.
 *
 * Adds procedure titles, adopted text titles, and pipeline health
 * indicators to the base keyword set.
 *
 * @param data - Propositions article data payload
 * @returns Deduplicated keyword array
 */
function buildPropositionsKeywords(data: PropositionsArticleData): string[] {
  const keywords: string[] = [...PROPOSITIONS_BASE_KEYWORDS];
 
  if (data.feedData?.procedures) {
    for (const proc of data.feedData.procedures.slice(0, 5)) {
      Eif (proc.title) keywords.push(proc.title.slice(0, 60));
    }
  }
  if (data.feedData?.adoptedTexts) {
    for (const text of data.feedData.adoptedTexts.slice(0, 3)) {
      Eif (text.title) keywords.push(text.title.slice(0, 60));
    }
  }
  if (data.pipelineData) {
    keywords.push('legislative pipeline');
    Eif (data.pipelineData.healthScore >= 0.8) keywords.push('healthy pipeline');
  }
 
  return [...new Set(keywords)];
}
 
/**
 * Build a content-aware description from propositions data.
 * Summarises pipeline health, procedure counts, and adopted text counts.
 *
 * @param data - Propositions article data payload
 * @returns SEO-friendly description (≤ 200 chars)
 */
function buildPropositionsDescription(data: PropositionsArticleData): string {
  const parts: string[] = [];
 
  const procCount = data.feedData?.procedures?.length ?? 0;
  const adoptedCount = data.feedData?.adoptedTexts?.length ?? 0;
  // Count proposals by the number of proposal-card divs in the HTML
  const proposalMatches = data.proposalsHtml.match(/proposal-card/gu);
  const proposalCount = proposalMatches ? proposalMatches.length : 0;
 
  if (proposalCount > 0) parts.push(`${proposalCount} active proposals`);
  if (procCount > 0) parts.push(`${procCount} procedures tracked`);
  if (adoptedCount > 0) parts.push(`${adoptedCount} recently adopted texts`);
  if (data.pipelineData) {
    const healthPct = Math.round(data.pipelineData.healthScore * 100);
    parts.push(`pipeline health ${healthPct}%`);
  }
 
  if (parts.length === 0) {
    return 'Recent legislative proposals, procedure tracking, and pipeline status in the European Parliament';
  }
 
  const desc = `EP legislative tracker: ${parts.join(', ')}.`;
  return desc.length > 200 ? desc.slice(0, 197) + '...' : desc;
}
 
/**
 * Build a content-aware title suffix from propositions data.
 *
 * @param data - Propositions article data payload
 * @returns Short suffix for the title, or empty string
 */
function buildPropositionsTitleSuffix(data: PropositionsArticleData): string {
  const parts: string[] = [];
  const procCount = data.feedData?.procedures?.length ?? 0;
  const adoptedCount = data.feedData?.adoptedTexts?.length ?? 0;
  if (procCount > 0) parts.push(pl(procCount, 'Procedure', 'Procedures'));
  if (adoptedCount > 0) parts.push(pl(adoptedCount, 'Adopted Text', 'Adopted Texts'));
  if (data.pipelineData && parts.length === 0) {
    const healthPct = Math.round(data.pipelineData.healthScore * 100);
    parts.push(`Pipeline ${healthPct}%`);
  }
  return parts.join(', ');
}
 
/**
 * Build procedures and adopted-texts HTML separately from EP feed data when
 * search_documents returns empty. Uses procedures and adopted texts from the
 * feed as fallback content, rendering each as a distinct section.
 *
 * @param feedData - EP feed data containing procedures and adopted texts
 * @returns Pre-sanitized HTML for procedures and adopted texts sections separately
 */
function buildProceduresAndAdoptedTextsFromFeed(feedData: EPFeedData): {
  proceduresHtml: string;
  adoptedTextsHtml: string;
} {
  const procedureItems: string[] = [];
  const adoptedTextItems: string[] = [];
 
  for (const proc of feedData.procedures.slice(0, 8)) {
    procedureItems.push(`
      <div class="proposal-card">
        <h3>${escapeHTML(proc.title || proc.id)}</h3>
        <div class="proposal-meta">
          <span class="proposal-id">${escapeHTML(proc.identifier ?? proc.id)}</span>
          ${proc.date ? `<span class="proposal-date">${escapeHTML(proc.date)}</span>` : ''}
          ${proc.stage ? `<span class="proposal-status">${escapeHTML(proc.stage)}</span>` : ''}
        </div>
      </div>`);
  }
 
  for (const text of feedData.adoptedTexts.slice(0, 8)) {
    adoptedTextItems.push(`
      <div class="proposal-card">
        <h3>${escapeHTML(text.title || text.id)}</h3>
        <div class="proposal-meta">
          <span class="proposal-id">${escapeHTML(text.identifier ?? text.id)}</span>
          ${text.date ? `<span class="proposal-date">${escapeHTML(text.date)}</span>` : ''}
        </div>
      </div>`);
  }
 
  return {
    proceduresHtml: procedureItems.join('\n'),
    adoptedTextsHtml: adoptedTextItems.join('\n'),
  };
}
 
// ─── Data payload ─────────────────────────────────────────────────────────────
 
/** Data fetched and pre-processed by {@link PropositionsStrategy} */
export interface PropositionsArticleData extends ArticleData {
  /** Pre-sanitised HTML for the legislative procedures list section */
  readonly proposalsHtml: string;
  /** Pre-sanitised HTML for the recently adopted texts section */
  readonly adoptedTextsHtml: string;
  /** Active legislative pipeline data (null when MCP unavailable) */
  readonly pipelineData: PipelineData | null;
  /** Pre-sanitised HTML for the tracked procedure section */
  readonly procedureHtml: string;
  /** EP feed data for enrichment (when available) */
  readonly feedData?: EPFeedData | undefined;
}
 
// ─── Strategy implementation ──────────────────────────────────────────────────
 
/**
 * Article strategy for {@link ArticleCategory.PROPOSITIONS}.
 * Fetches legislative proposals, active pipeline status, and procedure detail
 * then renders a language-specific article.
 */
export class PropositionsStrategy implements ArticleStrategy<PropositionsArticleData> {
  readonly type = ArticleCategory.PROPOSITIONS;
 
  readonly requiredMCPTools = [
    'search_documents',
    'monitor_legislative_pipeline',
    'track_legislation',
    'get_procedures_feed',
    'get_adopted_texts_feed',
  ] as const;
 
  /**
   * Fetch legislative proposals and pipeline data in parallel.
   *
   * @param client - MCP client or null
   * @param date - ISO 8601 publication date
   * @returns Populated propositions data payload
   */
  async fetchData(
    client: EuropeanParliamentMCPClient | null,
    date: string
  ): Promise<PropositionsArticleData> {
    const feedDateRange = computeRollingDateRange(date, 7, 'propositions feed window');
 
    if (client) {
      console.log('  📡 Fetching legislative data from MCP server...');
    }
 
    // Fetch proposals, pipeline, and EP feed data in parallel
    const [proposalsResult, pipelineResult, feedData] = await Promise.allSettled([
      fetchProposalsFromMCP(client),
      fetchPipelineFromMCP(client),
      fetchEPFeedData(client, 'one-week', feedDateRange),
    ]);
 
    const { html: proposalsHtml, firstProcedureId } =
      proposalsResult.status === 'fulfilled'
        ? proposalsResult.value
        : { html: '', firstProcedureId: '' };
 
    const pipelineData = pipelineResult.status === 'fulfilled' ? pipelineResult.value : null;
    const feedResult = feedData.status === 'fulfilled' ? feedData.value : undefined;
 
    const procedureHtml = await fetchProcedureStatusFromMCP(client, firstProcedureId);
 
    // When search_documents returns empty but feed data has procedures/adopted texts,
    // build proposals HTML from the feed data as fallback
    let finalProposalsHtml = proposalsHtml;
    let finalAdoptedTextsHtml = '';
    if (!finalProposalsHtml && feedResult) {
      const hasFeedItems = feedResult.procedures.length > 0 || feedResult.adoptedTexts.length > 0;
      Eif (hasFeedItems) {
        console.log(
          `  📰 Building procedures/adopted-texts from feed data: ${feedResult.procedures.length} procedures, ${feedResult.adoptedTexts.length} adopted texts`
        );
        const feedHtml = buildProceduresAndAdoptedTextsFromFeed(feedResult);
        finalProposalsHtml = feedHtml.proceduresHtml;
        finalAdoptedTextsHtml = feedHtml.adoptedTextsHtml;
      }
    }
 
    if (!finalProposalsHtml && !finalAdoptedTextsHtml) {
      console.log('  ℹ️ No proposals from MCP — pipeline article will be data-free');
    }
 
    return {
      date,
      proposalsHtml: finalProposalsHtml,
      adoptedTextsHtml: finalAdoptedTextsHtml,
      pipelineData,
      procedureHtml,
      feedData: feedResult,
    };
  }
 
  /**
   * Build the propositions HTML body using language-specific strings.
   *
   * @param data - Propositions data payload
   * @param lang - Target language code
   * @returns Article HTML body
   */
  buildContent(data: PropositionsArticleData, lang: LanguageCode): string {
    const strings = getLocalizedString(PROPOSITIONS_STRINGS, lang);
    const base = buildPropositionsContent(
      data.proposalsHtml,
      data.adoptedTextsHtml,
      data.pipelineData,
      data.procedureHtml,
      strings,
      lang
    );
    const analysis = buildPropositionsAnalysis(
      data.proposalsHtml,
      data.pipelineData,
      data.date,
      lang,
      data.adoptedTextsHtml
    );
    const deepSection = buildDeepAnalysisSection(analysis, lang, 'en');
    const mindmapData = buildPropositionsMindmap(data.pipelineData, lang);
    const mindmapSection = buildIntelligenceMindmapSection(mindmapData, lang);
    const swotData = buildPropositionsSwot(data.pipelineData, lang);
    const swotSection = buildSwotSection(swotData, lang);
    const dashboardData = buildPropositionsDashboard(data.pipelineData, lang);
    const dashboardSection = buildDashboardSection(dashboardData, lang);
    const injection = deepSection + mindmapSection + swotSection + dashboardSection;
    // Inject before the closing </div> of .article-content
    Eif (injection) {
      const closingTag = '</div>';
      const lastIdx = base.lastIndexOf(closingTag);
      Eif (lastIdx !== -1) {
        return base.slice(0, lastIdx) + injection + '\n' + base.slice(lastIdx);
      }
    }
    return base;
  }
 
  /**
   * Return language-specific metadata for the propositions article.
   *
   * @param data - Propositions data payload
   * @param lang - Target language code
   * @returns Localised metadata
   */
  getMetadata(data: PropositionsArticleData, lang: LanguageCode): ArticleMetadata {
    const titleFn = getLocalizedString(PROPOSITIONS_TITLES, lang);
    const { title: baseTitle, subtitle: baseSubtitle } = titleFn();
    const suffix = lang === 'en' ? buildPropositionsTitleSuffix(data) : '';
    const title = suffix ? `${baseTitle} — ${suffix}` : baseTitle;
    const helperSubtitle = lang === 'en' ? buildPropositionsDescription(data) : '';
    const subtitle = helperSubtitle || baseSubtitle;
    return {
      title,
      subtitle,
      keywords: buildPropositionsKeywords(data),
      category: ArticleCategory.PROPOSITIONS,
      sources: [],
    };
  }
}
 
/** Singleton instance for use by the strategy registry */
export const propositionsStrategy = new PropositionsStrategy();