All files / scripts/generate-news-indexes helpers.ts

81.96% Statements 150/183
80.1% Branches 153/191
83.78% Functions 31/37
83.12% Lines 133/160

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                                        1x 1x     1x   1x                                                                                                                           91263x 91263x 91263x 91157x 91157x 91263x   598x                       91263x                                 91263x 273789x 273789x 91263x 182679x 91249x             91264x 91264x 91264x     91264x 91264x 1x 1x     91263x         91263x     91264x         91264x 91264x                               91264x                           366314x 366314x 366314x     2774x 2774x 2774x     2774x 2774x 2774x   2774x 2774x 2774x   2774x                             91263x     91263x 1262x       90001x 90001x                               1210x   1210x 1210x   1196x 1196x     1196x 1196x 1196x                           14x 14x               121888x     121888x                                 2471436x 54581x       67307x                                 67307x   69971x 67270x       37x                                 1242x 4x     33x               91263x 91263x     91263x 93512x 93512x 93512x 93512x 93512x 93512x 93512x 93512x     91263x 91263x 638841x     91263x             91263x 91263x     91263x 93512x     91263x 30625x 30625x 30625x     201099x               78x 78x 78x 91988x 52x 91936x 91234x     78x               26x   26x   26x     26x 364x     26x 91234x   91234x   91234x   91234x 91234x           26x 451932x     26x 364x 364x 26x   26x             23x     23x 322x   80707x   80707x 80707x       80707x 1129898x 283200863x   283200863x 1063773x             23x    
/**
 * @module generate-news-indexes/helpers
 * @description Utility functions for article metadata parsing, topic/type
 * classification, news directory scanning, and cross-language discovery.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import type {
  LanguageConfig,
  NewsArticleMetadata,
  ArticleTypeValue,
} from './types.js';
import { LANGUAGES, LANGUAGE_FLAGS, AVAILABLE_IN_TRANSLATIONS } from './constants.js';
import { decodeHtmlEntities } from '../html-utils.js';
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
/** Root news directory */
export const NEWS_DIR: string = path.join(__dirname, '..', '..', 'news');
 
const TOPIC_INFERENCE_PATTERNS: ReadonlyArray<readonly [string, RegExp]> = [
  ['committees', /(committee|committeereports|utskott|betänkande|committee reports|rapport de commission|ausschuss|위원회|委员会|委員会)/i],
  ['legislation', /(proposition|motion|bill|legislative|lagstift|lovgiv|lainsäädäntö|gesetz|législation|legislación|立法|입법)/i],
  ['parliament', /(interpellation|riksdag|parliament|riksdagen|parlament|val\b|election|voting|vote|议会|의회|議会)/i],
  ['government', /(government|regering|regerings|minister|ministry|kristersson|gouvernement|gobierno|regierung|الحكومة|ממשלה|政府)/i],
  ['defense', /(defen[cs]e|försvar|forsvar|puolustus|verteidigung|défense|defensa|defensie|国防|防衛|국방)/i],
  ['environment', /(environment|climate|miljö|miljø|ympäristö|umwelt|environnement|medio ambiente|milieu|环境|環境|환경)/i],
  ['eu', /(eu|european union|europeiska unionen|union européenne|europäische union)/i],
] as const;
 
/**
 * Generate language badge HTML for an article.
 */
export function generateLanguageBadge(lang: string, isRTL: boolean = false): string {
  const flag: string = LANGUAGE_FLAGS[lang] || '🌐';
  const langUpper: string = lang.toUpperCase();
  const dirAttr: string = isRTL ? ' dir="ltr"' : '';
  return `<span class="language-badge"${dirAttr} aria-label="${(LANGUAGES as Record<string, LanguageConfig>)[lang]?.name || lang} language"><span aria-hidden="true">${flag}</span> ${langUpper}</span>`;
}
 
/**
 * Generate language switcher navigation for news index pages.
 */
export function generateLanguageSwitcherNav(currentLang: string): string {
  const langEntries: [string, LanguageConfig][] = Object.entries(LANGUAGES);
  const links: string = langEntries.map(([code, data]) => {
    const flag: string = LANGUAGE_FLAGS[code] || '🌐';
    const filename: string = code === 'en' ? 'index.html' : `index_${code}.html`;
    const activeClass: string = code === currentLang ? ' active' : '';
    // Norwegian files use filename suffix 'no' but must be advertised as 'nb' per BCP-47.
    const bcp47: string = code === 'no' ? 'nb' : code;
    // `lang=` ensures screen-readers pronounce the native language name
    // using the correct voice, independent of the page's <html lang>.
    return `  <a href="${filename}" class="lang-link${activeClass}" hreflang="${bcp47}" lang="${bcp47}">${flag} ${data.name}</a>`;
  }).join('\n');
  return `<nav class="language-switcher" role="navigation" aria-label="Language selection">\n${links}\n</nav>`;
}
 
/**
 * Generate "Available in" text with language badges.
 */
export function generateAvailableLanguages(languages: string[], currentLang: string): string {
  if (!languages || languages.length <= 1) return '';
 
  const isRTL: boolean = ['ar', 'he'].includes(currentLang);
  const availableText: string = AVAILABLE_IN_TRANSLATIONS[currentLang] || 'Available in';
  const badges: string = languages.map((lang) => generateLanguageBadge(lang, isRTL)).join(' ');
 
  return `<p class="available-languages"><strong>${availableText}:</strong> ${badges}</p>`;
}
 
 
/**
 * Extract the JSON-LD `description` field from a NewsArticle blob
 * embedded in the article HTML. Returns `null` when the script tag is
 * missing, malformed, or has no description. Used as a tertiary fallback
 * for `parseArticleMetadata` / `extractArticleMeta`, after `og:description`
 * and `<meta name="description">`.
 *
 * Implements `seo-metadata-contract.md` §3.h.
 */
export function extractDescriptionFromJSONLD(html: string): string | null {
  try {
    const jsonLdMatch = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/i);
    if (!jsonLdMatch) return null;
    const jsonData = JSON.parse(jsonLdMatch[1]!.trim()) as { description?: string };
    const desc = typeof jsonData.description === 'string' ? jsonData.description.trim() : '';
    return desc.length > 0 ? desc : null;
  } catch {
    return null;
  }
}
 
/**
 * Strip a trailing ` — Riksdagsmonitor` / ` | Riksdagsmonitor` brand
 * suffix from a title so sitemap / news-index cards render the editorial
 * headline alone. The brand is re-added by the card template.
 *
 * Implements `seo-metadata-contract.md` §3.h.
 */
export function stripBrandSuffix(title: string): string {
  return title.replace(/\s*[—\-|]\s*Riksdagsmonitor\s*$/i, '').trim();
}
 
/**
 * Choose the richest available description from three candidate sources,
 * preferring whichever is longest but non-empty. Falls back in order:
 *   1. `og:description` (often the richest, emitted by the aggregator)
 *   2. `<meta name="description">` (truncated legacy copy)
 *   3. JSON-LD `description` (last resort)
 *
 * Implements `seo-metadata-contract.md` §3.h.
 */
export function chooseBestDescription(
  ogDescription: string | null,
  metaDescription: string | null,
  jsonLdDescription: string | null,
): string {
  const candidates = [ogDescription, metaDescription, jsonLdDescription]
    .map((s) => (s ?? '').trim())
    .filter((s) => s.length > 0);
  if (candidates.length === 0) return '';
  candidates.sort((a, b) => b.length - a.length);
  return candidates[0]!;
}
 
/**
 * Parse HTML file to extract article metadata.
 */
export function parseArticleMetadata(filePath: string): NewsArticleMetadata | null {
  try {
    const content: string = fs.readFileSync(filePath, 'utf-8');
    const fileName: string = path.basename(filePath);
 
    // Extract language from filename (e.g., article-en.html → en, article-da.html → da)
    const langMatch: RegExpMatchArray | null = fileName.match(/-(en|sv|da|no|fi|de|fr|es|nl|ar|he|ja|ko|zh)\.html$/);
    if (!langMatch) {
      console.warn(`  ⚠️ Skipping ${fileName}: no language suffix`);
      return null;
    }
 
    const lang: string = langMatch[1]!;
 
    // Extract metadata from HTML meta tags
    // Decode HTML entities to UTF-8 to prevent double-escaping in index pages
    const rawTitle =
      extractMetaContent(content, 'og:title') ||
      extractTitle(content) ||
      'Untitled';
    const description = chooseBestDescription(
      extractMetaContent(content, 'og:description'),
      extractMetaContent(content, 'description'),
      extractDescriptionFromJSONLD(content),
    );
    const topics = extractTopics(content, fileName);
    const metadata: NewsArticleMetadata = {
      slug: fileName,
      lang,
      title: stripBrandSuffix(decodeHtmlEntities(rawTitle)),
      description: decodeHtmlEntities(description),
      date: normalizeDateString(
        extractMetaContent(content, 'article:published_time') ||
        extractMetaContent(content, 'date') ||
        extractDateFromJSONLD(content) ||
        extractFromFilename(fileName),
      ),
      type: classifyArticleType(content, fileName),
      topics,
      tags: decodeHtmlEntities(extractTags(content, fileName, topics).join('|||')).split('|||').filter(Boolean),
    };
 
    return metadata;
  } catch (error: unknown) {
    console.error(`  ❌ Error parsing ${path.basename(filePath)}:`, (error as Error).message);
    return null;
  }
}
 
/**
 * Extract content from meta tags.
 *
 * Fixed: regex now properly handles apostrophes and special characters in content.
 */
export function extractMetaContent(html: string, property: string): string | null {
  // Match double-quoted attributes
  const doubleQuotePattern = new RegExp(`<meta\\s+(?:property|name)="${property}"\\s+content="([^"]+)"`, 'i');
  const doubleQuoteMatch: RegExpMatchArray | null = html.match(doubleQuotePattern);
  if (doubleQuoteMatch) return doubleQuoteMatch[1]!;
 
  // Match single-quoted attributes
  const singleQuotePattern = new RegExp(`<meta\\s+(?:property|name)='${property}'\\s+content='([^']+)'`, 'i');
  const singleQuoteMatch: RegExpMatchArray | null = html.match(singleQuotePattern);
  Iif (singleQuoteMatch) return singleQuoteMatch[1]!;
 
  // Try reversed order (content before property/name)
  const reversedDoublePattern = new RegExp(`<meta\\s+content="([^"]+)"\\s+(?:property|name)="${property}"`, 'i');
  const reversedDoubleMatch: RegExpMatchArray | null = html.match(reversedDoublePattern);
  Iif (reversedDoubleMatch) return reversedDoubleMatch[1]!;
 
  const reversedSinglePattern = new RegExp(`<meta\\s+content='([^']+)'\\s+(?:property|name)='${property}'`, 'i');
  const reversedSingleMatch: RegExpMatchArray | null = html.match(reversedSinglePattern);
  Iif (reversedSingleMatch) return reversedSingleMatch[1]!;
 
  return null;
}
 
/**
 * Extract title from <title> tag.
 */
export function extractTitle(html: string): string | null {
  const match: RegExpMatchArray | null = html.match(/<title>([^<]+)<\/title>/i);
  return match ? match[1]!.replace(' - Riksdagsmonitor', '').trim() : null;
}
 
/**
 * Normalize date string to YYYY-MM-DD format.
 */
export function normalizeDateString(dateStr: string | null): string {
  Iif (!dateStr) return new Date().toISOString().split('T')[0]!;
 
  // If already in YYYY-MM-DD format, return as-is
  if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
    return dateStr;
  }
 
  // If ISO timestamp (with time), extract just the date part
  Eif (dateStr.includes('T')) {
    return dateStr.split('T')[0]!;
  }
 
  // If has timezone offset like +01:00, remove it first
  const cleaned: string = dateStr.replace(/[+-]\d{2}:\d{2}$/, '');
  if (cleaned.includes('T')) {
    return cleaned.split('T')[0]!;
  }
 
  return dateStr;
}
 
/**
 * Extract date from JSON-LD structured data.
 */
export function extractDateFromJSONLD(html: string): string | null {
  try {
    // Extract JSON-LD script tag content
    const jsonLdMatch: RegExpMatchArray | null = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/i);
    if (!jsonLdMatch) return null;
 
    const jsonLdText: string = jsonLdMatch[1]!.trim();
    const jsonData: { datePublished?: string } = JSON.parse(jsonLdText) as { datePublished?: string };
 
    // Extract datePublished from NewsArticle schema
    Eif (jsonData.datePublished) {
      const dateStr: string = jsonData.datePublished.split('T')[0]!;
      return dateStr;
    }
 
    return null;
  } catch {
    // Silently fail - this is a fallback mechanism
    return null;
  }
}
 
/**
 * Extract date from filename (YYYY-MM-DD format).
 */
export function extractFromFilename(fileName: string): string {
  const match: RegExpMatchArray | null = fileName.match(/^(\d{4}-\d{2}-\d{2})/);
  return match ? match[1]! : new Date().toISOString().split('T')[0]!;
}
 
/**
 * Classify article type based on content and filename.
 * Supports detection keywords in all 14 languages.
 */
export function classifyArticleType(content: string, fileName: string): ArticleTypeValue {
  const lowerContent: string = content.toLowerCase();
 
  // Prospective: week-ahead / upcoming previews
  const prospectiveKeywords: string[] = [
    'week ahead', 'week-ahead', 'upcoming', 'preview', 'look ahead',           // en
    'veckan som kommer', 'kommande vecka', 'framåtblick',                       // sv
    'ugen der kommer', 'kommende uge', 'fremadrettet',                          // da
    'uken som kommer', 'fremtidsrettet',                                        // no
    'tuleva viikko', 'ennakko',                                                 // fi
    'woche voraus', 'vorschau',                                                 // de
    'semaine à venir', 'aperçu',                                                // fr
    'semana por delante', 'adelanto',                                            // es
    'week vooruit', 'vooruitblik',                                               // nl
    'الأسبوع المقبل', 'القادم',                                                  // ar
    'השבוע הבא', 'הקרוב',                                                       // he
    '来週の展望', '今後',                                                          // ja
    '주간 전망', '다가오는',                                                       // ko
    '一周展望', '即将'                                                             // zh
  ];
 
  if (fileName.includes('week-ahead') || fileName.includes('month-ahead') || prospectiveKeywords.some((kw) => lowerContent.includes(kw.toLowerCase()))) {
    return 'prospective';
  }
 
  // Analysis: committee reports, propositions, motions
  const analysisKeywords: string[] = [
    'committee reports', 'analysis', 'review', 'assessment',                     // en
    'utskottsbetänkanden', 'analys', 'granskning', 'betänkande',                // sv
    'udvalgsrapporter', 'analyse', 'gennemgang', 'udvalgsbetænkning',           // da
    'komitérapporter', 'gjennomgang', 'komitéinnstilling',                      // no
    'valiokuntaraportit', 'analyysi', 'katsaus', 'valiokunnan mietintö',        // fi
    'ausschussberichte', 'überprüfung', 'ausschussbericht',                     // de
    'rapports de commission', 'examen', 'rapport de commission',                 // fr
    'informes de comité', 'análisis', 'revisión', 'informe de comité',          // es
    'commissierapporten', 'beoordeling', 'commissieverslag',                     // nl
    'تقارير اللجان', 'تحليل', 'تقرير اللجنة',                                  // ar
    'דוחות ועדות', 'ניתוח', 'דוח ועדה',                                         // he
    '委員会報告', '分析',                                                          // ja
    '위원회 보고서', '분석',                                                       // ko
    '委员会报告', '分析'                                                           // zh
  ];
 
  if (fileName.includes('committee-reports') || fileName.includes('propositions') || fileName.includes('motions') ||
      fileName.includes('deep-inspection') ||
      analysisKeywords.some((kw) => lowerContent.includes(kw.toLowerCase()))) {
    return 'analysis';
  }
 
  // Breaking: urgent/alert news
  const breakingKeywords: string[] = [
    'breaking', 'urgent', 'alert', 'flash',                                      // en
    'senaste nytt', 'akut', 'brådskande',                                        // sv
    'seneste nyt', 'hastesag',                                                   // da
    'siste nytt', 'haster',                                                      // no
    'viimeisimmät', 'kiireellinen', 'hälytys',                                   // fi
    'eilmeldungen', 'dringend', 'alarm',                                         // de
    'dernières nouvelles', 'alerte',                                              // fr
    'última hora', 'urgente', 'alerta',                                           // es
    'laatste nieuws', 'alert',                                                    // nl
    'أخبار عاجلة', 'عاجل',                                                       // ar
    'חדשות אחרונות', 'דחוף',                                                     // he
    '速報', '緊急',                                                               // ja
    '속보', '긴급',                                                               // ko
    '突发新闻', '紧急'                                                             // zh
  ];
 
  if (fileName.includes('breaking') || breakingKeywords.some((kw) => lowerContent.includes(kw.toLowerCase()))) {
    return 'breaking';
  }
 
  return 'retrospective';
}
 
/**
 * Extract topics from article tags.
 * Supports topic detection keywords in all 14 languages.
 */
export function extractTopics(content: string, fileName: string = ''): string[] {
  const topics: string[] = [];
  const tagPattern = /<meta\s+property=["']article:tag["']\s+content=["']([^"']+)["']/gi;
  let match: RegExpExecArray | null;
 
  while ((match = tagPattern.exec(content)) !== null) {
    const tag: string = match[1]!.toLowerCase();
    if (tag.includes('eu')) topics.push('eu');
    if (tag.includes('parliament') || tag.includes('riksdag') || tag.includes('parlamentet') || tag.includes('議会') || tag.includes('의회') || tag.includes('议会') || tag.includes('البرلمان') || tag.includes('פרלמנט')) topics.push('parliament');
    if (tag.includes('government') || tag.includes('regering') || tag.includes('regjeringen') || tag.includes('hallitus') || tag.includes('regierung') || tag.includes('gouvernement') || tag.includes('gobierno') || tag.includes('政府') || tag.includes('정부') || tag.includes('الحكومة') || tag.includes('ממשלה')) topics.push('government');
    if (tag.includes('defense') || tag.includes('defence') || tag.includes('försvar') || tag.includes('forsvar') || tag.includes('puolustus') || tag.includes('verteidigung') || tag.includes('défense') || tag.includes('defensa') || tag.includes('defensie') || tag.includes('الدفاع') || tag.includes('הגנה') || tag.includes('防衛') || tag.includes('국방') || tag.includes('国防')) topics.push('defense');
    if (tag.includes('environment') || tag.includes('miljö') || tag.includes('miljø') || tag.includes('ympäristö') || tag.includes('umwelt') || tag.includes('environnement') || tag.includes('medio ambiente') || tag.includes('milieu') || tag.includes('البيئة') || tag.includes('סביבה') || tag.includes('環境') || tag.includes('환경') || tag.includes('环境')) topics.push('environment');
    if (tag.includes('committee') || tag.includes('utskott') || tag.includes('udvalg') || tag.includes('utvalg') || tag.includes('valiokunt') || tag.includes('ausschuss') || tag.includes('commission') || tag.includes('comité') || tag.includes('commissie') || tag.includes('لجنة') || tag.includes('ועדה') || tag.includes('委員会') || tag.includes('위원회') || tag.includes('委员会')) topics.push('committees');
    if (tag.includes('legislation') || tag.includes('lagstiftning') || tag.includes('lovgivning') || tag.includes('lainsäädäntö') || tag.includes('gesetzgebung') || tag.includes('législation') || tag.includes('legislación') || tag.includes('wetgeving') || tag.includes('التشريعات') || tag.includes('חקיקה') || tag.includes('立法') || tag.includes('입법')) topics.push('legislation');
  }
 
  const sourceSample = `${fileName} ${content.slice(0, 2500)}`;
  for (const [topic, pattern] of TOPIC_INFERENCE_PATTERNS) {
    if (pattern.test(sourceSample)) topics.push(topic);
  }
 
  return [...new Set(topics)].slice(0, 5); // Unique, max 5
}
 
/**
 * Extract tags from article:tag meta tags.
 */
export function extractTags(content: string, fileName: string = '', inferredTopics?: string[]): string[] {
  const tags: string[] = [];
  const tagPattern = /<meta\s+property=["']article:tag["']\s+content=["']([^"']+)["']/gi;
  let match: RegExpExecArray | null;
 
  while ((match = tagPattern.exec(content)) !== null) {
    tags.push(match[1]!);
  }
 
  if (tags.length === 0) {
    inferredTopics ??= extractTopics(content, fileName);
    const inferredType = classifyArticleType(content, fileName);
    tags.push(inferredType, ...inferredTopics);
  }
 
  return [...new Set(tags.filter((tag) => tag.trim().length > 0))].slice(0, 4); // Max 4 tags for display
}
 
/**
 * Collect all article HTML file paths recursively from a directory.
 * Supports date-based subdirectory structure: news/{year}/{month}/article.html
 */
function collectArticleFiles(dir: string): string[] {
  const result: string[] = [];
  const entries = fs.readdirSync(dir, { withFileTypes: true });
  for (const entry of entries) {
    if (entry.isDirectory()) {
      result.push(...collectArticleFiles(path.join(dir, entry.name)));
    } else if (entry.isFile() && entry.name.endsWith('.html') && !entry.name.startsWith('index')) {
      result.push(path.join(dir, entry.name));
    }
  }
  return result;
}
 
/**
 * Scan news directory and group articles by language.
 * Supports date-based subdirectory structure: news/{year}/{month}/article.html
 */
export function scanNewsArticles(): Record<string, NewsArticleMetadata[]> {
  console.log('\n📰 Scanning for articles...');
 
  const filePaths: string[] = collectArticleFiles(NEWS_DIR);
 
  console.log(`  Found ${filePaths.length} article files`);
 
  // Initialize buckets for all 14 supported languages
  const articlesByLang: Record<string, NewsArticleMetadata[]> = Object.fromEntries(
    Object.keys(LANGUAGES).map((lang) => [lang, []]),
  );
 
  filePaths.forEach((filePath) => {
    const metadata: NewsArticleMetadata | null = parseArticleMetadata(filePath);
 
    Eif (metadata) {
      // Set slug to relative path from NEWS_DIR (e.g., "2026/02/2026-02-13-article-en.html")
      metadata.slug = path.relative(NEWS_DIR, filePath).split(path.sep).join('/');
 
      Eif (articlesByLang[metadata.lang]) {
        articlesByLang[metadata.lang]!.push(metadata);
      }
    }
  });
 
  // Sort by date descending (newest first)
  Object.keys(articlesByLang).forEach((lang) => {
    articlesByLang[lang]?.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  });
 
  const langCounts: string[] = Object.entries(articlesByLang)
    .filter(([, arr]) => arr.length > 0)
    .map(([lang, arr]) => `${lang.toUpperCase()} ${arr.length}`);
  console.log(`  📊 Articles by language: ${langCounts.length > 0 ? langCounts.join(', ') : 'none found'}`);
 
  return articlesByLang;
}
 
/**
 * Build map of base slugs to available languages for cross-language discovery.
 */
export function buildSlugToLanguagesMap(articlesByLang: Record<string, NewsArticleMetadata[]>): Record<string, string[]> {
  const slugToLanguages: Record<string, string[]> = {};
 
  // Iterate through all articles in all languages
  Object.entries(articlesByLang).forEach(([_lang, articles]) => {
    articles.forEach((article) => {
      // Strip language suffix from slug to get base slug
      const baseSlug: string = article.slug.replace(/-(en|sv|da|no|fi|de|fr|es|nl|ar|he|ja|ko|zh)\.html$/, '.html');
 
      Eif (!slugToLanguages[article.slug]) {
        slugToLanguages[article.slug] = [];
      }
 
      // Find all articles with the same base slug across languages
      Object.entries(articlesByLang).forEach(([otherLang, otherArticles]) => {
        otherArticles.forEach((otherArticle) => {
          const otherBaseSlug: string = otherArticle.slug.replace(/-(en|sv|da|no|fi|de|fr|es|nl|ar|he|ja|ko|zh)\.html$/, '.html');
 
          if (baseSlug === otherBaseSlug && !slugToLanguages[article.slug]!.includes(otherLang)) {
            slugToLanguages[article.slug]!.push(otherLang);
          }
        });
      });
    });
  });
 
  return slugToLanguages;
}