All files / scripts detect-swedish-leakage.ts

75.37% Statements 199/264
76.87% Branches 133/173
78.94% Functions 15/19
78.44% Lines 182/232

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 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784                                                        22x                         22x                                                                                                                                                                                                                                   22x                                     2662x                     363x 363x 363x 363x 363x   363x 7844950x 7679203x 7679203x     165747x 165747x 330164x 330164x   1331x 1331x   1331x 1331x   1331x 1331x 1331x   1331x 1331x   1331x 1331x     1331x 1328x       1331x 1331x     330164x   330164x 330164x 330164x 330164x     165747x 164416x         363x 361x     363x                 325057x 325057x 8878504x 8878504x 4696373x 4696373x   4182131x 251001x 251001x   3931130x                             325057x 325057x 325057x   325057x 325057x   325057x 6536x     318521x 318521x 325057x 325057x 325057x   325057x               173835x 173835x               173835x 12869x 12869x 12869x                 919x 919x   919x 919x 919x 12550x 1811x 1811x   1811x 927x 923x 923x 4x 4x     892x                                   334x 334x   334x   334x 334x 4493432x   159830x 159830x             159830x           458x 458x 458x 52013x   458x 458x       159372x     334x         113004x 113004x   113004x 8775844x 8775844x 163500x 163499x   163500x 163500x   8612344x 163057x 163057x   8449287x 4427289x       113004x                   113004x   113004x   29x       113004x       113004x 113004x                                       113004x                                 337x   337x 337x 4440997x 162497x 162497x   162497x           461x 461x                 461x 461x   461x 461x 461x   10x 10x 10x   461x 461x     162036x     337x                       336x 2x           334x       334x                 334x   334x 334x   334x   334x   334x 112514x 112514x   112514x 425215x     425215x 374x 26x 26x 17x             425215x 11423x 10573x 10573x 814x               334x 831x       831x   334x               22x                                                       374x 374x               22x                                                                   11423x 11423x                                                                                                                                                                               22x     22x            
/**
 * @module Swedish Leakage Detector
 * @description Detects untranslated Swedish text in non-Swedish articles.
 *
 * Scans HTML content for Swedish-specific tokens that should have been
 * translated. Reports leaked terms with their positions and a leakage score.
 *
 * Typically used as an advisory CI check: the script exits non-zero if any
 * non-SV article contains ≥ threshold untranslated Swedish tokens, but CI
 * workflows may choose to run it with `continue-on-error`.
 *
 * Usage:
 *   npx tsx scripts/detect-swedish-leakage.ts --dir news/ --threshold 5
 */
 
import { join, resolve } from 'path';
import { fileURLToPath } from 'url';
import type { Language } from './types/language.js';
 
// ---------------------------------------------------------------------------
// Swedish-only vocabulary – high-confidence tokens that are exclusively Swedish
// and should never appear in correctly translated content.
// ---------------------------------------------------------------------------
 
/**
 * Common Swedish function words that are almost never valid in other languages.
 * Each word is a lower-case Swedish term.
 */
export const SWEDISH_STOP_WORDS: ReadonlySet<string> = new Set([
  'och', 'att', 'det', 'som', 'är', 'för', 'med', 'har', 'den',
  'inte', 'ska', 'kan', 'till', 'ett', 'var', 'blir', 'också',
  'efter', 'vid', 'eller', 'från', 'dessa', 'samt', 'enligt',
  'genom', 'inom', 'redan', 'dels', 'bland', 'dock', 'även',
  'mellan', 'under', 'utan', 'sedan', 'bör', 'hos', 'mot',
]);
 
/**
 * Swedish parliamentary terms that should always be translated.
 * These are domain-specific Swedish words that should never appear in e.g. English articles.
 * Includes common inflected forms (definite, plural, genitive) to catch actual leaked tokens.
 */
export const SWEDISH_PARLIAMENTARY_TERMS: ReadonlySet<string> = new Set([
  // Betänkande (committee report) – base + common inflections
  'betänkande', 'betänkanden', 'betänkandet', 'betänkandena',
  // Proposition (government bill)
  'proposition', 'propositionen', 'propositioner', 'propositionerna',
  // Utskott (committee)
  'utskott', 'utskottet', 'utskotten', 'utskottets', 'utskottens',
  // Riksdag (parliament)
  'riksdag', 'riksdagen', 'riksdagens',
  // Regering (government)
  'regering', 'regeringen', 'regeringens',
  // Motion (member's bill)
  'motion', 'motionen', 'motioner', 'motionerna', 'motionens',
  // Interpellation (formal question)
  'interpellation', 'interpellationen', 'interpellationer', 'interpellationerna',
  // Anförande (speech)
  'anförande', 'anförandet', 'anföranden', 'anförandena',
  // Votering / omröstning (vote)
  'votering', 'voteringen', 'voteringar', 'voteringarna',
  'omröstning', 'omröstningen', 'omröstningar', 'omröstningarna',
  // Bordläggning (tabling)
  'bordläggning', 'bordläggningen',
  // Remiss / yttrande (referral / opinion)
  'remiss', 'remissen', 'remisser', 'remisserna',
  'yttrande', 'yttrandet', 'yttranden', 'yttrandena',
  // Statsråd / ledamot / riksdagsledamot (minister / member of parliament)
  'statsråd', 'statsrådet', 'statsråden',
  'ledamot', 'ledamoten', 'ledamöter', 'ledamöterna',
  'riksdagsledamot', 'riksdagsledamoten', 'riksdagsledamöter', 'riksdagsledamöterna',
  // Budget terms
  'utgiftsområde', 'utgiftsområdet', 'utgiftsområden',
  'budgetpropositionen', 'vårpropositionen',
  // Committee names (already definite form)
  'finansutskottet', 'justitieutskottet', 'försvarsutskottet',
  'socialutskottet', 'utbildningsutskottet', 'utrikesutskottet',
  'skatteutskottet', 'trafikutskottet', 'kulturutskottet',
  // Other procedure terms
  'tillkännagivande', 'tillkännagivanden', 'tillkännagivandet',
  'lagförslag', 'lagförslaget', 'lagförslagen',
  'lagstiftning', 'lagstiftningen',
  'sammanträde', 'sammanträdet', 'sammanträden',
  'anmälan', 'anmälningar', 'anmälningarna',
  'granskning', 'granskningen', 'granskningar',
  'beredning', 'beredningen', 'beredningar',
  'anslag', 'anslaget', 'anslagen',
  'utgiftstak', 'utgiftstaket',
  'statsbudgeten',
  // Swedish government ministries (departement) – should always be translated
  'finansdepartementet',
  'utrikesdepartementet',
  'justitiedepartementet',
  'försvarsdepartementet',
  'utbildningsdepartementet',
  'socialdepartementet',
  'kulturdepartementet',
  'miljödepartementet',
  'infrastrukturdepartementet',
  'arbetsmarknadsdepartementet',
  'näringsdepartementet',
]);
 
/** Result for a single detected leaked term. */
export interface LeakedTerm {
  /** The Swedish token detected. */
  readonly term: string;
  /** 1-based line number where the term was first found. */
  readonly line: number;
  /** Number of occurrences of this term in the article. */
  readonly count: number;
}
 
/** Aggregated leakage report for a single article. */
export interface LeakageReport {
  /** Array of leaked Swedish terms found (deduplicated, with per-term counts). */
  readonly leakedTerms: ReadonlyArray<LeakedTerm>;
  /** Total number of Swedish token occurrences detected across all leaked terms. */
  readonly score: number;
  /**
   * Large `<span lang="sv">` blocks (≥ {@link LARGE_SV_SPAN_WORD_THRESHOLD}
   * Swedish words) found in a non-SV article. Populated by
   * {@link detectSwedishLeakage} since §P0-3 of the agentic-workflow quality
   * plan: these are *always* a hard-fail regardless of the dictionary-score
   * bucket, because they indicate untranslated Swedish source material
   * reaching a target-language reader.
   *
   * Empty for SV articles and for non-SV articles with no large untranslated
   * blocks.
   */
  readonly largeSwedishSpans?: ReadonlyArray<LargeSwedishSpan>;
}
 
/**
 * Details of a large `<span lang="sv">` block detected in a non-SV article.
 * A block is "large" when it contains at least {@link LARGE_SV_SPAN_WORD_THRESHOLD}
 * words of recognisable Swedish text.
 */
export interface LargeSwedishSpan {
  /** 1-based line number where the opening tag starts. */
  readonly line: number;
  /** Total word count inside the span (after whitespace normalisation). */
  readonly wordCount: number;
  /** Excerpt of the Swedish content (first ~120 chars, whitespace-collapsed). */
  readonly excerpt: string;
}
 
/**
 * Word-count threshold above which a `<span lang="sv">` in a non-SV article
 * is treated as an automatic hard-fail (§P0-3).
 *
 * Eight words is large enough to catch untranslated titles and summary
 * dumps (e.g. `"accessibilityskrav för vissa medier"` plus a short clause)
 * while leaving space for legitimate short proper-noun quotations like
 * committee names or ministry titles that are < 8 words long.
 */
export const LARGE_SV_SPAN_WORD_THRESHOLD = 8;
 
// ---------------------------------------------------------------------------
// HTML stripping helper
// ---------------------------------------------------------------------------
 
/**
 * Options for stripHtml processing.
 *
 * skipBlockStripping: Set to true when script/style blocks have already been
 * removed by a prior pass (e.g. line-preserving preprocessing in detectSwedishLeakage)
 * to avoid redundant block stripping work.
 */
interface StripHtmlOptions {
  readonly skipBlockStripping?: boolean;
}
 
/** Valid boundary after an HTML tag name. */
function isTagNameBoundary(ch: string | undefined): boolean {
  return ch === undefined || ch === '>' || ch === '/' || /\s/.test(ch);
}
 
/**
 * Strip specific HTML tag blocks using a single-pass index-based scan
 * (avoids regex tag filters and repeated toLowerCase).
 *
 * For preserveNewlines=true, removed content is replaced with spaces while keeping '\n'
 * positions intact so line numbering remains stable.
 */
function stripTagBlocks(html: string, tagNames: ReadonlyArray<string>, preserveNewlines: boolean): string {
  const lower = html.toLowerCase();
  const length = html.length;
  const resultParts: string[] = [];
  let copyFrom = 0;
  let i = 0;
 
  while (i < length) {
    if (lower[i] !== '<') {
      i++;
      continue;
    }
 
    let matchedBlock = false;
    for (const tagName of tagNames) {
      const openPrefix = `<${tagName}`;
      if (!lower.startsWith(openPrefix, i)) continue;
 
      const openNameBoundaryIndex = i + 1 + tagName.length;
      Iif (!isTagNameBoundary(lower[openNameBoundaryIndex])) continue;
 
      const openEnd = lower.indexOf('>', openNameBoundaryIndex);
      Iif (openEnd === -1) continue;
 
      const closePrefix = `</${tagName}`;
      const closeStart = lower.indexOf(closePrefix, openEnd + 1);
      Iif (closeStart === -1) continue;
 
      const closeNameBoundaryIndex = closeStart + 2 + tagName.length;
      Iif (!isTagNameBoundary(lower[closeNameBoundaryIndex])) continue;
 
      const closeEnd = lower.indexOf('>', closeNameBoundaryIndex);
      Iif (closeEnd === -1) continue;
 
      // Push text before this block
      if (i > copyFrom) {
        resultParts.push(html.slice(copyFrom, i));
      }
 
      // Push replacement for the matched block
      const block = html.slice(i, closeEnd + 1);
      const replacement = preserveNewlines
        ? block.replace(/[^\n]/g, ' ')
        : ' ';
      resultParts.push(replacement);
 
      i = closeEnd + 1;
      copyFrom = i;
      matchedBlock = true;
      break;
    }
 
    if (!matchedBlock) {
      i++;
    }
  }
 
  // Push remaining text after the last matched block
  if (copyFrom < length) {
    resultParts.push(html.slice(copyFrom));
  }
 
  return resultParts.join('');
}
 
/**
 * Locate the closing `>` of an HTML tag starting at `startIndex`, correctly skipping
 * quoted attribute values so that `>` inside `"..."` or `'...'` is not treated as the tag end.
 * Returns -1 when no closing `>` is found.
 */
function findTagEnd(html: string, startIndex: number): number {
  let quote: '"' | "'" | null = null;
  for (let i = startIndex + 1; i < html.length; i++) {
    const ch = html[i];
    if (quote !== null) {
      if (ch === quote) quote = null;
      continue;
    }
    if (ch === '"' || ch === "'") {
      quote = ch;
      continue;
    }
    if (ch === '>') return i;
  }
  return -1;
}
 
interface ParsedTag {
  tagEnd: number;
  tagName: string | null;
  isClosing: boolean;
  isSelfClosing: boolean;
  rawTag: string;
}
 
/** Parse the tag starting at `startIndex`; returns null if no `<` is at that position. */
function parseTagAt(html: string, startIndex: number): ParsedTag | null {
  Iif (html[startIndex] !== '<') return null;
  const tagEnd = findTagEnd(html, startIndex);
  Iif (tagEnd === -1) return null;
 
  const rawTag = html.slice(startIndex, tagEnd + 1);
  const inner = rawTag.slice(1, -1).trim();
  // Skip comments, DOCTYPE, and processing instructions.
  if (inner.length === 0 || inner.startsWith('!') || inner.startsWith('?')) {
    return { tagEnd, tagName: null, isClosing: false, isSelfClosing: false, rawTag };
  }
 
  const isClosing = inner.startsWith('/');
  const nameSource = isClosing ? inner.slice(1).trimStart() : inner;
  const nameMatch = /^([a-zA-Z][a-zA-Z0-9:-]*)/.exec(nameSource);
  const tagName = nameMatch ? nameMatch[1].toLowerCase() : null;
  const isSelfClosing = !isClosing && /\/\s*>$/.test(rawTag);
 
  return { tagEnd, tagName, isClosing, isSelfClosing, rawTag };
}
 
/** Extract the value of the `lang` attribute from a raw tag string, or null if absent. */
function getLangAttributeValue(rawTag: string): string | null {
  // Require `lang` to be a standalone attribute name — preceded by `<` (tag-start) or
  // whitespace — so attributes like `data-lang` or `xml:lang` are not mistakenly treated
  // as `lang`.
  const m = /(?:<|\s)lang\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/i.exec(rawTag);
  return m?.[1] ?? m?.[2] ?? m?.[3] ?? null;
}
 
/**
 * Check whether a `lang` attribute value matches the given language code,
 * supporting BCP-47 subtags (e.g. `sv-SE` matches `sv`, `sv-FI` matches `sv`).
 */
function langMatches(langValue: string | null, langCode: string): boolean {
  if (!langValue || !langCode) return false;
  const v = langValue.toLowerCase();
  const c = langCode.toLowerCase();
  return v === c || v.startsWith(`${c}-`);
}
 
/**
 * Find the index of the matching closing tag for the element opened at `openingTagStart`.
 * Uses depth tracking to correctly handle nested elements with the same tag name.
 * Returns the index of the final `>` of the closing tag, or -1 when not found.
 */
function findMatchingTaggedBlockEnd(html: string, openingTagStart: number, tagName: string): number {
  const opening = parseTagAt(html, openingTagStart);
  Iif (!opening) return -1;
 
  let depth = 1;
  let i = opening.tagEnd + 1;
  while (i < html.length) {
    if (html[i] !== '<') { i++; continue; }
    const parsed = parseTagAt(html, i);
    Iif (!parsed) break;
 
    if (parsed.tagName === tagName) {
      if (parsed.isClosing) {
        depth--;
        if (depth === 0) return parsed.tagEnd;
      } else if (E!parsed.isSelfClosing) {
        depth++;
      }
    }
    i = parsed.tagEnd + 1;
  }
  return -1;
}
 
/**
 * Strip the inner contents of any HTML element whose `lang` attribute matches `langCode`
 * (including BCP-47 subtags — `lang="sv-SE"` matches `langCode="sv"`). Uses an index-based
 * tag scanner with depth tracking so nested elements of the same tag name are handled
 * correctly, and quoted attribute values containing `>` do not break parsing.
 *
 * The full matched block is replaced with whitespace while `\n` characters are preserved
 * so downstream line numbering stays stable.
 *
 * This enables `detectSwedishLeakage` to correctly ignore deliberately quoted Swedish source
 * material (e.g. verbatim summaries) embedded inside `<span lang="sv">...</span>` wrappers.
 */
function stripLangTaggedBlocks(html: string, langCode: string): string {
  const safeLang = langCode.replace(/[^a-zA-Z0-9-]/g, '').toLowerCase();
  Iif (safeLang.length === 0) return html;
 
  const chars = html.split('');
 
  let i = 0;
  while (i < html.length) {
    if (html[i] !== '<') { i++; continue; }
 
    const parsed = parseTagAt(html, i);
    Iif (!parsed) {
      // Malformed markup (stray `<` in text, etc.) — skip this character and keep
      // scanning so later lang-tagged blocks are still stripped.
      i++;
      continue;
    }
 
    if (
      !parsed.isClosing &&
      !parsed.isSelfClosing &&
      parsed.tagName !== null &&
      langMatches(getLangAttributeValue(parsed.rawTag), safeLang)
    ) {
      const blockEnd = findMatchingTaggedBlockEnd(html, i, parsed.tagName);
      Eif (blockEnd !== -1) {
        for (let j = i; j <= blockEnd; j++) {
          if (chars[j] !== '\n') chars[j] = ' ';
        }
        i = blockEnd + 1;
        continue;
      }
    }
 
    i = parsed.tagEnd + 1;
  }
 
  return chars.join('');
}
 
/** Remove all remaining HTML tags using an index-based state machine. */
function stripAllTags(html: string): string {
  const chunks: string[] = [];
  let inTag = false;
 
  for (let i = 0; i < html.length; i++) {
    const ch = html[i];
    if (ch === '<') {
      if (!inTag) {
        chunks.push(' ');
      }
      inTag = true;
      continue;
    }
    if (ch === '>' && inTag) {
      inTag = false;
      continue;
    }
    if (!inTag) {
      chunks.push(ch);
    }
  }
 
  return chunks.join('');
}
 
/**
 * Strip HTML tags and decode common entities to get plain text.
 * This is used only for analysis/detection purposes, NOT for sanitisation.
 * @param html - Raw HTML string
 * @returns Plain text content
 */
export function stripHtml(html: string, options: StripHtmlOptions = {}): string {
  let text = html;
 
  if (!options.skipBlockStripping) {
    // Remove script/style blocks first to avoid matching inner tag-like content.
    text = stripTagBlocks(text, ['script', 'style'], false);
  }
 
  // Remove remaining tags
  text = stripAllTags(text);
  // Decode common entities.
  // First, decode doubly-encoded entity references (&amp;#xE4; → &#xE4;) so that
  // the subsequent hex/numeric patterns can match them in a single pass.
  text = text.replace(/&amp;(#\w+;)/g, '&$1');
  text = text
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&#0*39;|&#[xX]0*27;/g, "'")
    .replace(/&nbsp;/g, ' ')
    // Swedish characters (HTML named and numeric entities, case-insensitive hex)
    .replace(/&auml;|&#228;|&#[xX]0*[eE]4;/g, 'ä')
    .replace(/&Auml;|&#196;|&#[xX]0*[cC]4;/g, 'Ä')
    .replace(/&ouml;|&#246;|&#[xX]0*[fF]6;/g, 'ö')
    .replace(/&Ouml;|&#214;|&#[xX]0*[dD]6;/g, 'Ö')
    .replace(/&aring;|&#229;|&#[xX]0*[eE]5;/g, 'å')
    .replace(/&Aring;|&#197;|&#[xX]0*[cC]5;/g, 'Å')
    // Common quote and dash entities (case-insensitive hex, optional leading zeros)
    .replace(/&ndash;|&#8211;|&#[xX]0*2013;/g, '-')
    .replace(/&mdash;|&#8212;|&#[xX]0*2014;/g, '-')
    .replace(/&ldquo;|&rdquo;|&#8220;|&#8221;|&#[xX]0*201[Cc];|&#[xX]0*201[Dd];/g, '"')
    .replace(/&lsquo;|&rsquo;|&#8216;|&#8217;|&#[xX]0*2018;|&#[xX]0*2019;|&apos;/g, "'")
    .replace(/&amp;/g, '&');
  // Normalise whitespace
  return text.replace(/\s+/g, ' ').trim();
}
 
// ---------------------------------------------------------------------------
// Core detection logic
// ---------------------------------------------------------------------------
 
/**
 * Find every `<span lang="sv">...</span>` block in the HTML and return those
 * whose inner-text word-count meets or exceeds the "large" threshold
 * (§P0-3 hard-fail bucket). Used only for non-SV articles — callers must
 * short-circuit for SV articles before invoking this helper.
 *
 * Depth-aware: handles nested spans correctly so a `<span lang="sv">` that
 * contains an inner `<span>` is treated as a single block.
 */
export function findLargeSwedishSpans(html: string): ReadonlyArray<LargeSwedishSpan> {
  const results: LargeSwedishSpan[] = [];
 
  let i = 0;
  while (i < html.length) {
    if (html[i] !== '<') { i++; continue; }
    const parsed = parseTagAt(html, i);
    Iif (!parsed) { i++; continue; }
 
    if (
      !parsed.isClosing &&
      !parsed.isSelfClosing &&
      parsed.tagName !== null &&
      langMatches(getLangAttributeValue(parsed.rawTag), 'sv')
    ) {
      const blockEnd = findMatchingTaggedBlockEnd(html, i, parsed.tagName);
      Eif (blockEnd !== -1) {
        // Offset math: `parsed.tagEnd` = index of the `>` that closes the
        // opening tag; the block's inner text therefore starts at
        // `parsed.tagEnd + 1`. `blockEnd` = index of the `>` that closes the
        // closing tag (`</tagName>`, which is `tagName.length + 3` chars long
        // for the `<`, `/`, and `>`). So the first index of the closing tag
        // itself is `blockEnd - closingTagLen + 1`, and `slice(start, end)`
        // excludes that index — which is exactly what we want (inner content
        // only, no closing tag).
        const closingTagLen = parsed.tagName.length + 3;
        const inner = html.slice(parsed.tagEnd + 1, blockEnd - closingTagLen + 1);
        // Inner may contain child HTML; strip tags to get plain words only.
        const plain = stripHtml(inner, { skipBlockStripping: true });
        const words = plain.split(/\s+/).filter(Boolean);
        if (words.length >= LARGE_SV_SPAN_WORD_THRESHOLD) {
          // 1-based line number of the opening tag.
          const line = html.slice(0, i).split('\n').length;
          const excerpt = plain.length > 120 ? plain.slice(0, 117) + '...' : plain;
          results.push({ line, wordCount: words.length, excerpt });
        }
        i = blockEnd + 1;
        continue;
      }
    }
    i = parsed.tagEnd + 1;
  }
 
  return results;
}
 
/**
 * Detect Swedish leakage in HTML content intended for a non-Swedish audience.
 *
 * @param html       - Full article HTML
 * @param targetLang - The article's target language (e.g. 'en', 'de')
 * @returns LeakageReport with leaked terms and score
 */
export function detectSwedishLeakage(html: string, targetLang: Language): LeakageReport {
  // Swedish articles are expected to contain Swedish text.
  if (targetLang === 'sv') {
    return { leakedTerms: [], score: 0, largeSwedishSpans: [] };
  }
 
  // §P0-3: Identify `<span lang="sv">` blocks ≥ 8 Swedish words BEFORE we
  // strip them, so callers can hard-fail on untranslated source-material
  // dumps even when the dictionary-score bucket is under threshold.
  const largeSwedishSpans = findLargeSwedishSpans(html);
 
  // Strip script/style blocks on the full HTML first so multi-line blocks are
  // removed correctly. Preserve newline count so reported line numbers remain accurate.
  let cleaned = stripTagBlocks(html, ['script', 'style'], true);
 
  // Strip elements explicitly tagged as Swedish content (e.g. `<span lang="sv">...</span>`).
  // Text inside a `lang="sv"` element is deliberately quoted Swedish source material
  // (e.g. verbatim summaries from riksdagen.se) and MUST NOT count as translation leakage
  // in a non-Swedish article. This call is only reached for non-Swedish targets because
  // `targetLang === 'sv'` short-circuits with an empty report above, so legitimate Swedish
  // text in Swedish articles is never removed. Replacement preserves '\n' so reported line
  // numbers stay accurate.
  cleaned = stripLangTaggedBlocks(cleaned, 'sv');
 
  const lines = cleaned.split('\n');
  const leaked: LeakedTerm[] = [];
  /** First-seen line for each term. */
  const firstLine = new Map<string, number>();
  /** Per-term occurrence count. */
  const counts = new Map<string, number>();
 
  for (let i = 0; i < lines.length; i++) {
    const plainLine = stripHtml(lines[i], { skipBlockStripping: true });
    const words = plainLine.split(/[-\s,.:;!?()[\]{}'"]+/).filter(Boolean);
 
    for (const word of words) {
      const lower = word.toLowerCase();
 
      // Check against Swedish stop words (require ≥2 chars to avoid false positives)
      if (lower.length >= 2 && SWEDISH_STOP_WORDS.has(lower)) {
        if (!isSharedWord(lower, targetLang)) {
          counts.set(lower, (counts.get(lower) ?? 0) + 1);
          if (!firstLine.has(lower)) {
            firstLine.set(lower, i + 1);
          }
        }
      }
 
      // Check against Swedish parliamentary terms, also applying shared-word filter
      // to avoid false positives in Scandinavian languages (e.g. "proposition" shared across languages)
      if (SWEDISH_PARLIAMENTARY_TERMS.has(lower)) {
        if (!isSharedParliamentaryTerm(lower, targetLang)) {
          counts.set(lower, (counts.get(lower) ?? 0) + 1);
          if (!firstLine.has(lower)) {
            firstLine.set(lower, i + 1);
          }
        }
      }
    }
  }
 
  // Build deduplicated results with counts
  for (const [term, line] of firstLine) {
    leaked.push({ term, line, count: counts.get(term) ?? 1 });
  }
 
  // Score: total number of Swedish token occurrences detected across all leaked terms
  const totalOccurrences = Array.from(counts.values()).reduce((sum, value) => sum + value, 0);
 
  return { leakedTerms: leaked, score: totalOccurrences, largeSwedishSpans };
}
 
// ---------------------------------------------------------------------------
// Shared word filter – some Swedish words are valid in other languages
// ---------------------------------------------------------------------------
 
/** Words shared between Swedish and specific other languages. */
const SHARED_WORDS: Partial<Record<Language, ReadonlySet<string>>> = {
  // Danish shares some common words with Swedish but not 'och', 'att', 'från' etc.
  da: new Set(['det', 'den', 'var', 'kan', 'efter', 'eller', 'under', 'mot', 'med', 'som', 'har']),
  // Norwegian shares some common words with Swedish
  no: new Set(['det', 'den', 'var', 'kan', 'eller', 'under', 'mot', 'med', 'som', 'har']),
  // German: do not treat "det" or "var" as shared, to avoid hiding Swedish leakage
  de: new Set([]),
  // Dutch: currently no Swedish stop words are treated as shared
  nl: new Set([]),
  fr: new Set([]),
  es: new Set([]),
  fi: new Set([]),
  // English shares a very small set of these short common forms with Swedish (e.g. "under"
  // can appear legitimately in technical or proper-noun contexts). Keep this set narrow
  // and limited to tokens that are genuinely ambiguous in English prose.
  en: new Set(['under']),
  ar: new Set([]),
  he: new Set([]),
  ja: new Set([]),
  ko: new Set([]),
  zh: new Set([]),
};
 
/**
 * Check if a Swedish word is also a valid word in the target language,
 * to avoid false positives (e.g. "det" in Danish).
 */
function isSharedWord(word: string, targetLang: Language): boolean {
  const shared = SHARED_WORDS[targetLang];
  return shared ? shared.has(word) : false;
}
 
/**
 * Parliamentary terms that are valid/identical in specific Scandinavian target
 * languages and should not be flagged as Swedish leakage for those languages.
 * Includes inflected forms to match the expanded SWEDISH_PARLIAMENTARY_TERMS set.
 */
const SHARED_PARLIAMENTARY_TERMS: Partial<Record<Language, ReadonlySet<string>>> = {
  // English political writing about Sweden uses "Riksdag" (and inflections) verbatim —
  // it has no common English equivalent. Other parliamentary terms (proposition, motion,
  // interpellation, anförande, statsråd, regering) should still be translated and are
  // intentionally NOT shared here, consistent with the translation quality gate tests.
  en: new Set([
    'riksdag', 'riksdagen', 'riksdagens',
  ]),
  // Norwegian uses many of the same parliamentary terms as Swedish
  no: new Set([
    'proposition', 'propositionen', 'propositioner', 'propositionerna',
    'interpellation', 'interpellationen', 'interpellationer', 'interpellationerna',
    'regeringen', 'regeringens',
    'statsråd', 'statsrådet', 'statsråden',
    // Only keep ministry names whose spelling is truly identical in Swedish and Norwegian.
    // Swedish-only spellings (försvarsdepartementet, miljödepartementet,
    // arbetsmarknadsdepartementet, näringsdepartementet) are NOT shared —
    // Norwegian uses distinct forms, so Swedish spellings should be flagged.
    'finansdepartementet',
    'kulturdepartementet',
    'infrastrukturdepartementet',
  ]),
  // Danish shares some parliamentary vocabulary
  da: new Set([
    'proposition', 'propositionen', 'propositioner', 'propositionerna',
    'interpellation', 'interpellationen', 'interpellationer', 'interpellationerna',
    'regeringen', 'regeringens',
  ]),
};
 
/**
 * Check if a Swedish parliamentary term is also valid in the target language.
 */
function isSharedParliamentaryTerm(term: string, targetLang: Language): boolean {
  const shared = SHARED_PARLIAMENTARY_TERMS[targetLang];
  return shared ? shared.has(term) : false;
}
 
// ---------------------------------------------------------------------------
// CLI entry point
// ---------------------------------------------------------------------------
 
async function main(): Promise<void> {
  const args = process.argv.slice(2);
  let dir = 'news/';
  let threshold = 5;
 
  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--dir' && args[i + 1]) {
      dir = args[i + 1];
      i++;
    }
    if (args[i] === '--threshold' && args[i + 1]) {
      const rawThreshold = args[i + 1];
      // Validate: must be a positive integer (optional leading zeros allowed, e.g. "03")
      if (!/^0*[1-9]\d*$/.test(rawThreshold)) {
        console.error(`Invalid --threshold value "${rawThreshold}". Threshold must be a positive integer.`);
        process.exit(1);
      }
      const parsed = Number(rawThreshold);
      if (!Number.isInteger(parsed) || parsed <= 0) {
        console.error(`Invalid --threshold value "${rawThreshold}". Threshold must be a positive integer.`);
        process.exit(1);
      }
      threshold = parsed;
      i++;
    }
  }
 
  const { readdirSync, readFileSync } = await import('fs');
  const files = readdirSync(dir).filter((f: string) => f.endsWith('.html'));
 
  const langCodes: ReadonlyArray<Language> = [
    'en', 'da', 'no', 'fi', 'de', 'fr', 'es', 'nl', 'ar', 'he', 'ja', 'ko', 'zh',
  ];
 
  let totalFailures = 0;
 
  for (const langCode of langCodes) {
    const langFiles = files.filter((f: string) => f.endsWith(`-${langCode}.html`));
 
    for (const file of langFiles) {
      const html = readFileSync(join(dir, file), 'utf-8');
      const report = detectSwedishLeakage(html, langCode);
 
      // §P0-3 HARD-FAIL BUCKET: any non-SV article containing a <span lang="sv">
      // block with ≥ LARGE_SV_SPAN_WORD_THRESHOLD Swedish words is an automatic
      // failure, independent of the dictionary-score threshold. This closes the
      // loophole where untranslated titles/summaries hid inside lang="sv"
      // wrappers and were excluded from the score.
      const largeSpans = report.largeSwedishSpans ?? [];
      if (largeSpans.length > 0) {
        console.error(
          `❌ ${file}: ${largeSpans.length} large <span lang="sv"> block(s) ` +
          `(≥ ${LARGE_SV_SPAN_WORD_THRESHOLD} Swedish words) — HARD FAIL (§P0-3)`
        );
        for (const span of largeSpans.slice(0, 5)) {
          console.error(`   Line ${span.line}: ${span.wordCount} words — "${span.excerpt}"`);
        }
        totalFailures++;
        continue; // do not double-count as score failure
      }
 
      if (report.score >= threshold) {
        console.error(`❌ ${file}: ${report.score} Swedish tokens detected (threshold: ${threshold})`);
        for (const t of report.leakedTerms.slice(0, 5)) {
          console.error(`   Line ${t.line}: "${t.term}" (×${t.count})`);
        }
        totalFailures++;
      }
    }
  }
 
  if (totalFailures > 0) {
    console.error(`\n${totalFailures} file(s) exceeded the Swedish leakage threshold.`);
    process.exit(1);
  } else {
    console.log('✅ All non-Swedish articles passed Swedish leakage check.');
  }
}
 
// Run CLI when invoked directly
const isMainModule =
  typeof process !== 'undefined' &&
  typeof process.argv?.[1] === 'string' &&
  resolve(fileURLToPath(import.meta.url)) === resolve(process.argv[1]);
Iif (isMainModule) {
  main().catch((err) => {
    console.error(err);
    process.exit(1);
  });
}