All files / scripts validate-news-translations.ts

0% Statements 0/283
0% Branches 0/178
0% Functions 0/13
0% Lines 0/278

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * @module Validation/TranslationQuality
 * @category Validation
 *
 * @title News Article Translation Completeness Validator
 *
 * @description
 * Validates that news articles published in non-Swedish languages are
 * fully translated, preventing partially-translated articles from publication.
 * Checks both data-translate markers AND actual untranslated English/Swedish
 * body content by comparing translated articles against their EN source.
 *
 * @author Hack23 AB (Multilingual Intelligence & Quality Assurance)
 * @license Apache-2.0
 * @version 3.0.0
 */
 
import { readFileSync, readdirSync, existsSync, statSync } from 'fs';
import { join, basename, dirname } from 'path';
 
import type { Language } from './types/language.js';
 
// ---------------------------------------------------------------------------
// Terminal colour codes
// ---------------------------------------------------------------------------
 
interface Colors {
  readonly reset: string;
  readonly green: string;
  readonly red: string;
  readonly yellow: string;
  readonly cyan: string;
  readonly bold: string;
}
 
const colors: Colors = {
  reset: '\x1b[0m',
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  cyan: '\x1b[36m',
  bold: '\x1b[1m',
};
 
// Language codes to check (exclude Swedish)
const NON_SWEDISH_LANGS: readonly Language[] = [
  'en', 'da', 'no', 'fi', 'de', 'fr', 'es', 'nl', 'ar', 'he', 'ja', 'ko', 'zh',
];
 
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
 
interface CheckResultPassed {
  readonly passed: true;
  readonly error?: undefined;
  readonly markerCount?: undefined;
  readonly samples?: undefined;
}
 
interface CheckResultFailed {
  readonly passed: false;
  readonly markerCount: number;
  readonly samples: string[];
  readonly error?: undefined;
}
 
interface CheckResultError {
  readonly passed?: undefined;
  readonly error: string;
  readonly markerCount?: undefined;
  readonly samples?: undefined;
}
 
type CheckResult = CheckResultPassed | CheckResultFailed | CheckResultError;
 
interface FailedFileRecord {
  readonly filename: string;
  readonly lang: string;
  readonly count: number;
  readonly samples: string[];
}
 
/** Record for files with untranslated body content (English or Swedish leakage) */
interface ContentLeakageRecord {
  readonly filename: string;
  readonly lang: string;
  readonly untranslatedParagraphs: number;
  readonly phraseMatches: number;
  readonly totalParagraphs: number;
  readonly percentUntranslated: number;
  readonly samples: string[];
}
 
/** Record for files containing unresolved AI_MUST_REPLACE markers in HTML comments */
interface AIMarkerFileRecord {
  readonly filename: string;
  readonly lang: string;
  readonly markerCount: number;
  readonly samples: string[];
}
 
// ---------------------------------------------------------------------------
// English / Swedish body-content leakage detection
// ---------------------------------------------------------------------------
 
/**
 * Minimum paragraph character length to consider for leakage checks.
 * Short fragments like dates or single words are skipped.
 */
const MIN_PARAGRAPH_LENGTH = 40;
 
/**
 * Regex patterns that match opening-through-closing script/style tags,
 * handling whitespace and attributes in closing tags (e.g. </script > or </style\tbar>).
 * Hoisted to module level to avoid repeated compilation per file.
 */
const SCRIPT_TAG_RE = /<script\b[^<]*(?:(?!<\/script\b)<[^<]*)*<\/script\b[^>]*>/gi;
const STYLE_TAG_RE = /<style\b[^<]*(?:(?!<\/style\b)<[^<]*)*<\/style\b[^>]*>/gi;
 
/**
 * English phrases that MUST NOT appear verbatim in non-EN translations.
 * These indicate untranslated analytical body content.
 */
const ENGLISH_LEAKAGE_PHRASES: readonly RegExp[] = [
  /\bThe pace of activity signals\b/i,
  /\bbroad legislative push\b/i,
  /\bculmination of legislative review\b/i,
  /\bcascade through committee deliberations\b/i,
  /\bStandard parliamentary procedures\b/i,
  /\bWhile parliament deliberates\b/i,
  /\bWhy It Matters\b/i,
  /\bPolicy Context\b/i,
  /\bCoalition Dynamics\b/i,
  /\bStakeholder Impact\b/i,
  /\bForward Indicators\b/i,
  /\bRead the full proposition\b/i,
  /\bLive intelligence platform for Swedish Parliament\b/i,
  /\bSwedish cybersecurity consultancy specializing\b/i,
  /\bAI-generated political intelligence based on OSINT\b/i,
  /\bThe outcomes of these proceedings will cascade\b/i,
  /\bThe legislative activity reflects the ongoing interplay\b/i,
  /\bopposition parties have mounted coordinated responses\b/i,
  /\banalysis confidence:/i,
  /\bThis article is supported by structured political intelligence\b/i,
];
 
/**
 * Swedish phrases that MUST NOT appear in non-SV articles.
 * These indicate raw API text that was not translated.
 */
const SWEDISH_LEAKAGE_PHRASES: readonly RegExp[] = [
  /Regeringen överlämnar denna/,
  /till riksdagen/,
  /riksdagen\.?\s*Stockholm den/,
  /Riksrevisionens rapport om/,
  /med anledning av prop\./,
  /med anledning av skr\./,
  /Skyddet för yttrandefriheten/,
  /Åtgärder mot social dumpning/,
  /Regeringens integrationspolitik/,
  /Nationell plan för nya datacenter/,
  /Funktionsrätt Sveriges granskning/,
  /Polismyndighetens myndighetsutövning/,
  /Fördelning av ansvar för infrastrukturkostnader/,
  /Statligt säkerställande av bra vård/,
];
 
/**
 * Extract visible text paragraphs from HTML body content.
 * Strips tags, scripts, styles; returns non-trivial paragraphs.
 *
 * NOTE: This is a best-effort HTML text extraction helper for validator
 * comparisons, not a full HTML parser. Because it is used for leakage
 * detection, extraction correctness matters: missed script/style/tag
 * stripping can reduce comparison accuracy. The iterative approach is
 * intended to remove nested script/style content more completely.
 */
function extractBodyParagraphs(html: string): string[] {
  // Reset lastIndex for module-level regexes (they carry state with /g flag)
  SCRIPT_TAG_RE.lastIndex = 0;
  STYLE_TAG_RE.lastIndex = 0;
 
  // Use iterative removal to fully strip script/style blocks.
  let cleaned = html;
  let prev = '';
  while (prev !== cleaned) {
    prev = cleaned;
    cleaned = cleaned.replace(SCRIPT_TAG_RE, '');
  }
  prev = '';
  while (prev !== cleaned) {
    prev = cleaned;
    cleaned = cleaned.replace(STYLE_TAG_RE, '');
  }
 
  // Extract paragraph text
  const paragraphs: string[] = [];
  const pRegex = /<p[^>]*>([\s\S]*?)<\/p>/gi;
  let match: RegExpExecArray | null;
  while ((match = pRegex.exec(cleaned)) !== null) {
    // Strip remaining HTML tags from paragraph content (text-only comparison, not for rendering)
    let text = match[1] ?? '';
    // Iteratively remove any surviving tags
    let prevText = '';
    while (prevText !== text) {
      prevText = text;
      text = text.replace(/<[^>]*>/g, '');
    }
    text = text.replace(/\s+/g, ' ').trim();
    if (text.length >= MIN_PARAGRAPH_LENGTH) {
      paragraphs.push(text);
    }
  }
  return paragraphs;
}
 
/**
 * Check how many paragraphs from an EN source appear verbatim in a translated article.
 * Returns an object with leakage metrics.
 */
function checkBodyContentLeakage(
  translatedFilePath: string,
  enSourcePath: string | null,
  fileLang: string,
): ContentLeakageRecord | null {
  // Skip EN files — they are the source
  if (fileLang === 'en') return null;
 
  const translatedContent = readFileSync(translatedFilePath, 'utf-8');
  const filename = basename(translatedFilePath);
  const translatedParagraphs = extractBodyParagraphs(translatedContent);
 
  if (translatedParagraphs.length === 0) return null;
 
  let enParagraphLeakageCount = 0;
  let phraseLeakageCount = 0;
  const samples: string[] = [];
 
  // 1. Check for English paragraph leakage from EN source
  if (enSourcePath && existsSync(enSourcePath)) {
    const enContent = readFileSync(enSourcePath, 'utf-8');
    const enParagraphs = extractBodyParagraphs(enContent);
    // Use a Set for O(1) lookup instead of O(n) array.includes()
    const translatedParagraphSet = new Set(translatedParagraphs);
 
    for (const enPara of enParagraphs) {
      if (enPara.length >= MIN_PARAGRAPH_LENGTH && translatedParagraphSet.has(enPara)) {
        enParagraphLeakageCount++;
        if (samples.length < 5) {
          samples.push(`[EN leakage] ${enPara.slice(0, 100)}...`);
        }
      }
    }
  }
 
  // 2. Check for known English boilerplate phrases
  for (const pattern of ENGLISH_LEAKAGE_PHRASES) {
    if (pattern.test(translatedContent)) {
      phraseLeakageCount++;
      const m = translatedContent.match(pattern);
      if (m && samples.length < 5) {
        samples.push(`[EN phrase] ${m[0]}`);
      }
    }
  }
 
  // 3. Check for Swedish raw text leakage in non-Swedish translated files
  //    that reach this point (EN files return early above because they are the source)
  if (fileLang !== 'sv') {
    for (const pattern of SWEDISH_LEAKAGE_PHRASES) {
      if (pattern.test(translatedContent)) {
        phraseLeakageCount++;
        const m = translatedContent.match(pattern);
        if (m && samples.length < 5) {
          samples.push(`[SV leakage] ${m[0]}`);
        }
      }
    }
  }
 
  const totalParagraphs = translatedParagraphs.length;
  // Percentage is based on EN paragraph leakage only; phrase matches are reported separately.
  const percentUntranslated = totalParagraphs > 0
    ? Math.round((enParagraphLeakageCount / totalParagraphs) * 100)
    : 0;
  const hasLeakage = enParagraphLeakageCount > 0 || phraseLeakageCount > 0;
 
  if (!hasLeakage) return null;
 
  if (phraseLeakageCount > 0 && samples.length < 5) {
    samples.unshift(`[Phrase matches] ${phraseLeakageCount} English/Swedish leakage phrase match(es) detected.`);
  }
 
  return {
    filename,
    lang: fileLang,
    untranslatedParagraphs: enParagraphLeakageCount,
    phraseMatches: phraseLeakageCount,
    totalParagraphs,
    percentUntranslated,
    samples,
  };
}
 
/**
 * Derive the EN source file path from a translated file path.
 * e.g. news/2026-04-09-committee-reports-de.html → news/2026-04-09-committee-reports-en.html
 */
function deriveEnSourcePath(filepath: string): string | null {
  const dir = dirname(filepath);
  const name = basename(filepath);
  const enName = name.replace(/-[a-z]{2}\.html$/, '-en.html');
  if (enName === name) return null; // couldn't derive
  const enPath = join(dir, enName);
  return existsSync(enPath) ? enPath : null;
}
 
/** BCP-47 validation error record */
export interface BCP47Error {
  readonly field: string;
  readonly expected: string;
  readonly actual: string;
}
 
/**
 * Map from filename language suffix to the expected BCP-47 tag used in
 * `html[lang]`, `og:locale`, and JSON-LD `inLanguage`.
 *
 * Norwegian files use the filename suffix 'no' but must be advertised as 'nb'.
 */
const BCP47_TAG: Record<string, string> = {
  en: 'en', sv: 'sv', da: 'da', no: 'nb', fi: 'fi',
  de: 'de', fr: 'fr', es: 'es', nl: 'nl',
  ar: 'ar', he: 'he', ja: 'ja', ko: 'ko', zh: 'zh',
};
 
const OG_LOCALE_EXPECTED: Record<string, string> = {
  en: 'en_US', sv: 'sv_SE', da: 'da_DK', no: 'nb_NO', fi: 'fi_FI',
  de: 'de_DE', fr: 'fr_FR', es: 'es_ES', nl: 'nl_NL',
  ar: 'ar_SA', he: 'he_IL', ja: 'ja_JP', ko: 'ko_KR', zh: 'zh_CN',
};
 
/**
 * Validate BCP-47 consistency within an article file.
 * Checks that `html[lang]`, `og:locale`, and JSON-LD `inLanguage` are
 * consistent with the expected values for the file's language suffix.
 */
export function validateBCP47Consistency(filePath: string, fileLang: string): BCP47Error[] {
  const errors: BCP47Error[] = [];
  const content = readFileSync(filePath, 'utf-8');
  const expectedTag = BCP47_TAG[fileLang] ?? fileLang;
  const expectedLocale = OG_LOCALE_EXPECTED[fileLang];
 
  // Check html lang attribute
  const htmlLangMatch = content.match(/<html\s[^>]*lang="([^"]+)"/);
  if (htmlLangMatch) {
    const actual = htmlLangMatch[1] ?? '';
    if (actual !== expectedTag) {
      errors.push({ field: 'html[lang]', expected: expectedTag, actual });
    }
  }
 
  // Check og:locale
  if (expectedLocale) {
    const ogMatch = content.match(/property="og:locale"\s+content="([^"]+)"/);
    if (ogMatch) {
      const actual = ogMatch[1] ?? '';
      if (actual !== expectedLocale) {
        errors.push({ field: 'og:locale', expected: expectedLocale, actual });
      }
    }
  }
 
  // Check JSON-LD inLanguage
  const inLangMatch = content.match(/"inLanguage":\s*"([^"]+)"/);
  if (inLangMatch) {
    const actual = inLangMatch[1] ?? '';
    if (actual !== expectedTag) {
      errors.push({ field: 'inLanguage', expected: expectedTag, actual });
    }
  }
 
  // Check dir="rtl" for RTL languages
  if (fileLang === 'ar' || fileLang === 'he') {
    if (!content.includes('dir="rtl"')) {
      errors.push({ field: 'dir', expected: 'rtl', actual: 'missing' });
    }
  }
 
  return errors;
}
 
// ---------------------------------------------------------------------------
// Functions
// ---------------------------------------------------------------------------
 
/**
 * Check if a file contains untranslated Swedish content markers.
 */
function checkFileForUntranslatedContent(filepath: string): CheckResult {
  try {
    const content = readFileSync(filepath, 'utf-8');
    const markers = content.match(/data-translate="true"/g);
 
    if (!markers) {
      return { passed: true };
    }
 
    // Extract samples of untranslated content
    const samples: string[] = [];
    const sampleRegex = /<span data-translate="true"[^>]*>([^<]{0,80})/g;
    let match: RegExpExecArray | null;
    let count = 0;
 
    while ((match = sampleRegex.exec(content)) !== null && count < 3) {
      const raw = match[1] ?? '';
      const text = raw.length >= 80 ? raw + '...' : raw;
      samples.push(text);
      count++;
    }
 
    return {
      passed: false,
      markerCount: markers.length,
      samples,
    };
  } catch (error: unknown) {
    return {
      error: (error as Error).message,
    };
  }
}
 
/**
 * Regex to detect unresolved AI_MUST_REPLACE markers in HTML comments.
 * These markers are embedded by content generators and MUST be replaced
 * by AI agents before publication. They should never appear in translated articles.
 *
 * Pattern matches: <!-- AI_MUST_REPLACE: ... -->
 */
const AI_MUST_REPLACE_COMMENT_RE = /<!--[\s\S]*?AI_MUST_REPLACE[\s\S]*?-->/g;
 
/**
 * Check if a file contains unresolved AI_MUST_REPLACE markers in HTML comments.
 * These are quality failures that must be fixed before publication.
 */
function checkFileForAIMustReplaceMarkers(filepath: string): AIMarkerFileRecord | null {
  try {
    const content = readFileSync(filepath, 'utf-8');
    AI_MUST_REPLACE_COMMENT_RE.lastIndex = 0;
    const allMatches = content.match(AI_MUST_REPLACE_COMMENT_RE);
    if (!allMatches || allMatches.length === 0) return null;
 
    const filename = basename(filepath);
    const lang = getLanguageCode(filename) ?? '';
 
    // Collect up to 3 sample marker names for reporting
    const samples: string[] = [];
    const nameRe = /AI_MUST_REPLACE:\s*([\w_]+)/g;
    let m: RegExpExecArray | null;
    while ((m = nameRe.exec(content)) !== null && samples.length < 3) {
      const name = m[1] ?? '';
      if (name && !samples.includes(name)) {
        samples.push(name);
      }
    }
 
    return { filename, lang, markerCount: allMatches.length, samples };
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed to validate AI_MUST_REPLACE markers in ${filepath}: ${message}`, { cause: error });
  }
}
 
/**
 * Get all HTML files in a directory (recursive).
 */
function getAllHtmlFiles(dir: string): string[] {
  const files: string[] = [];
 
  try {
    const items = readdirSync(dir);
 
    for (const item of items) {
      const fullPath = join(dir, item);
      const stat = statSync(fullPath);
 
      if (stat.isDirectory()) {
        files.push(...getAllHtmlFiles(fullPath));
      } else if (item.endsWith('.html')) {
        files.push(fullPath);
      }
    }
  } catch (error: unknown) {
    console.error(
      `${colors.red}Error reading directory ${dir}: ${(error as Error).message}${colors.reset}`,
    );
  }
 
  return files;
}
 
/**
 * Determine language code from filename.
 */
function getLanguageCode(filename: string): string | null {
  const match = filename.match(/-([a-z]{2})\.html$/);
  return match ? match[1] ?? null : null;
}
 
/**
 * Main validation function.
 */
function validateNewsTranslations(directory: string = 'news'): number {
  console.log(`${colors.bold}${colors.cyan}===========================================`);
  console.log(`News Article Translation Validation`);
  console.log(`===========================================${colors.reset}\n`);
  console.log(`Checking directory: ${directory}\n`);
 
  const htmlFiles = getAllHtmlFiles(directory);
  const nonSwedishFiles = htmlFiles.filter((file) => {
    const lang = getLanguageCode(basename(file));
    return lang !== null && (NON_SWEDISH_LANGS as readonly string[]).includes(lang);
  });
 
  console.log(`Found ${nonSwedishFiles.length} non-Swedish article files to check\n`);
 
  let totalPassed = 0;
  let totalFailed = 0;
  let totalErrors = 0;
  let totalBCP47Errors = 0;
  let totalContentLeakage = 0;
  let totalAIMarkers = 0;
  const failedFiles: FailedFileRecord[] = [];
  const leakageFiles: ContentLeakageRecord[] = [];
  const aiMarkerFiles: AIMarkerFileRecord[] = [];
 
  for (const filepath of nonSwedishFiles) {
    const filename = basename(filepath);
    const lang = getLanguageCode(filename);
    const result = checkFileForUntranslatedContent(filepath);
 
    // BCP-47 consistency check
    const bcp47Errors = lang ? validateBCP47Consistency(filepath, lang) : [];
    if (bcp47Errors.length > 0) {
      totalBCP47Errors += bcp47Errors.length;
      console.log(`${colors.yellow}⚠ BCP-47: ${filename}${colors.reset}`);
      for (const err of bcp47Errors) {
        console.log(`  ${colors.yellow}${err.field}: expected "${err.expected}", got "${err.actual}"${colors.reset}`);
      }
    }
 
    // AI_MUST_REPLACE marker check — unresolved placeholders in HTML comments
    // are a hard failure: they indicate the AI did not replace template content.
    const aiMarkerRecord = checkFileForAIMustReplaceMarkers(filepath);
    if (aiMarkerRecord) {
      aiMarkerFiles.push(aiMarkerRecord);
      totalAIMarkers += aiMarkerRecord.markerCount;
      const sampleStr = aiMarkerRecord.samples.length > 0
        ? ` [${aiMarkerRecord.samples.join(', ')}]`
        : '';
      console.log(`${colors.red}✗ AI_MUST_REPLACE: ${filename} — ${aiMarkerRecord.markerCount} unresolved marker(s)${sampleStr}${colors.reset}`);
    }
 
    // Body content leakage check (EN/SV text in non-EN/SV articles)
    // Leakage is computed here but only counted in summary totals for
    // marker-passed files (see below) to keep the summary math correct.
    let fileLeakage: ContentLeakageRecord | null = null;
    if (lang && lang !== 'en') {
      const enSourcePath = deriveEnSourcePath(filepath);
      fileLeakage = checkBodyContentLeakage(filepath, enSourcePath, lang);
      if (fileLeakage) {
        leakageFiles.push(fileLeakage);
        const paraMsg = fileLeakage.untranslatedParagraphs > 0
          ? `${fileLeakage.untranslatedParagraphs} leaked paragraph(s) (${fileLeakage.percentUntranslated}% of ${fileLeakage.totalParagraphs})`
          : '';
        const phraseMsg = fileLeakage.phraseMatches > 0
          ? `${fileLeakage.phraseMatches} phrase match(es)`
          : '';
        const combined = [paraMsg, phraseMsg].filter(Boolean).join(', ');
        console.log(`${colors.yellow}⚠ Content leakage: ${filename} — ${combined}${colors.reset}`);
        for (const sample of fileLeakage.samples.slice(0, 3)) {
          console.log(`  ${colors.yellow}  ${sample}${colors.reset}`);
        }
      }
    }
 
    if (result.error !== undefined) {
      console.log(`${colors.red}ERROR: ${filename}${colors.reset}`);
      console.log(`  ${colors.red}${result.error}${colors.reset}\n`);
      totalErrors++;
    } else if (result.passed) {
      // Files with AI_MUST_REPLACE markers are NOT counted as passed — they
      // are a separate hard failure reported via aiMarkerFiles.
      if (aiMarkerRecord) {
        // Already logged above; don't double-count as passed.
      } else {
        console.log(`${colors.green}✓ ${filename} (${(lang ?? '').toUpperCase()})${colors.reset}`);
        totalPassed++;
      }
      // Only count leakage toward summary totals for marker-passed files
      if (fileLeakage && !aiMarkerRecord) {
        totalContentLeakage++;
      }
    } else {
      console.log(`${colors.red}✗ ${filename} (${(lang ?? '').toUpperCase()})${colors.reset}`);
      console.log(
        `  ${colors.red}Found ${result.markerCount} untranslated marker(s)${colors.reset}`,
      );
 
      if (result.samples.length > 0) {
        console.log(`  ${colors.yellow}Samples:${colors.reset}`);
        result.samples.forEach((sample, i) => {
          console.log(`    ${i + 1}. "${sample}"`);
        });
      }
      console.log('');
 
      failedFiles.push({
        filename,
        lang: lang ?? '',
        count: result.markerCount,
        samples: result.samples,
      });
      totalFailed++;
    }
  }
 
  // Summary
  console.log(`\n${colors.bold}${colors.cyan}===========================================`);
  console.log(`Summary`);
  console.log(`===========================================${colors.reset}\n`);
  console.log(`Total articles checked: ${nonSwedishFiles.length}`);
  if (totalContentLeakage > 0) {
    // When leakage warnings exist, clarify that "passed" means marker checks only
    const fullyClean = totalPassed - totalContentLeakage;
    if (fullyClean > 0) {
      console.log(`${colors.green}✓ Fully translated: ${fullyClean}${colors.reset}`);
    }
    console.log(`${colors.green}✓ Marker check passed (with leakage warnings): ${totalContentLeakage}${colors.reset}`);
  } else {
    console.log(`${colors.green}✓ Fully translated: ${totalPassed}${colors.reset}`);
  }
  console.log(
    `${colors.red}✗ Contains untranslated content: ${totalFailed}${colors.reset}`,
  );
 
  if (totalErrors > 0) {
    console.log(`${colors.red}✗ Errors: ${totalErrors}${colors.reset}`);
  }
 
  if (totalBCP47Errors > 0) {
    console.log(`${colors.red}✗ BCP-47 inconsistencies: ${totalBCP47Errors}${colors.reset}`);
  }
 
  if (totalAIMarkers > 0) {
    console.log(`${colors.red}✗ Unresolved AI_MUST_REPLACE markers: ${totalAIMarkers} in ${aiMarkerFiles.length} article(s)${colors.reset}`);
  }
 
  if (totalContentLeakage > 0) {
    console.log(`${colors.yellow}⚠ Articles with EN/SV body content leakage: ${totalContentLeakage}${colors.reset}`);
  }
 
  const hasHardFailures = totalFailed > 0 || totalBCP47Errors > 0 || aiMarkerFiles.length > 0;
  // Content leakage is a warning that will become a hard failure when translation
  // workflows are updated. For now, report but don't block.
 
  if (hasHardFailures) {
    console.log(`\n${colors.bold}${colors.red}❌ VALIDATION FAILED${colors.reset}`);
 
    if (failedFiles.length > 0) {
      console.log(`\nFiles needing translation:\n`);
      failedFiles.forEach(({ filename, count }) => {
        console.log(`  ${colors.red}✗${colors.reset} ${filename} - ${count} markers`);
      });
 
      console.log(`\n${colors.yellow}Action Required:${colors.reset}`);
      console.log(`1. Open each file listed above`);
      console.log(
        `2. Find all <span data-translate="true" lang="sv">Swedish text</span> elements`,
      );
      console.log(`3. Translate the Swedish text to the article's target language`);
      console.log(`4. Replace the span with plain translated text`);
      console.log(`5. Consult TRANSLATION_GUIDE.md for terminology\n`);
    }
 
    if (aiMarkerFiles.length > 0) {
      console.log(`\n${colors.yellow}AI_MUST_REPLACE Action Required:${colors.reset}`);
      console.log(`The following articles contain unresolved AI_MUST_REPLACE placeholders in HTML comments.`);
      console.log(`The AI translation agent MUST replace these with genuine content in the target language:\n`);
      aiMarkerFiles.forEach(({ filename, markerCount, samples }) => {
        const sampleStr = samples.length > 0 ? ` [${samples.join(', ')}]` : '';
        console.log(`  ${colors.red}✗${colors.reset} ${filename} - ${markerCount} marker(s)${sampleStr}`);
      });
      console.log(`\n${colors.yellow}Fix:${colors.reset}`);
      console.log(`1. Open the source EN article and the translated article`);
      console.log(`2. Find every <!-- AI_MUST_REPLACE: ... --> comment`);
      console.log(`3. Replace the entire comment with genuine analysis in the target language`);
      console.log(`4. Re-run the translation workflow with updated prompts\n`);
    }
 
    if (totalBCP47Errors > 0) {
      console.log(`\n${colors.yellow}BCP-47 Action Required:${colors.reset}`);
      console.log(`Ensure html[lang], og:locale, and inLanguage are consistent per article.`);
      console.log(`Norwegian articles must use lang="nb", og:locale="nb_NO", inLanguage="nb".\n`);
    }
 
    return 1;
  }
 
  if (leakageFiles.length > 0) {
    console.log(`\n${colors.bold}${colors.yellow}⚠ TRANSLATION QUALITY WARNING${colors.reset}`);
    console.log(`\n${colors.yellow}Articles with untranslated English/Swedish body content:${colors.reset}\n`);
    for (const rec of leakageFiles) {
      const paraMsg = rec.untranslatedParagraphs > 0
        ? `${rec.untranslatedParagraphs} leaked paragraph(s) (${rec.percentUntranslated}% of ${rec.totalParagraphs})`
        : '';
      const phraseMsg = rec.phraseMatches > 0
        ? `${rec.phraseMatches} phrase match(es)`
        : '';
      const combined = [paraMsg, phraseMsg].filter(Boolean).join(', ');
      console.log(`  ${colors.yellow}⚠${colors.reset} ${rec.filename} — ${combined}`);
    }
    console.log(`\n${colors.yellow}Action Required:${colors.reset}`);
    console.log(`1. The translation workflow MUST translate ALL body paragraphs to the target language`);
    console.log(`2. Raw Swedish API text (interpellation/proposition excerpts) must be translated or summarized`);
    console.log(`3. English analytical paragraphs must not appear verbatim in non-EN articles`);
    console.log(`4. Re-run the news-translate workflow with improved prompts\n`);
    // Return warning exit code (0 for now, will become 1 when workflow is updated)
    return 0;
  }
 
  console.log(
    `\n${colors.bold}${colors.green}✅ ALL ARTICLES FULLY TRANSLATED${colors.reset}\n`,
  );
  return 0;
}
 
// Run validation
const directory: string = process.argv[2] || 'news';
const exitCode: number = validateNewsTranslations(directory);
 
process.exit(exitCode);