// Reproduction of Tactic Remote website's image-link bug, 2026-09-15.
// Adapted from the real URL helper before/after the fix (types removed).
// Runs only in memory: no network requests, file writes, or dependencies.
// Run on your development computer: node image-link-regression.mjs
import assert from 'node:assert/strict';

const locales = ['en', 'zh-CN', 'zh-TW', 'ja', 'ko', 'es', 'de', 'fr'];
const external = ['http://', 'https://', 'mailto:', 'tel:', '//', '#'];
function localizePathname(locale, pathname) {
  const clean = pathname.split('?')[0]?.split('#')[0] ?? '/';
  const parts = clean.split('/').filter(Boolean);
  const base = parts.length > 0 && locales.includes(parts[0])
    ? `/${parts.slice(1).join('/')}`.replace(/\/+$/, '') || '/'
    : clean || '/';
  const localized = locale === 'en' ? base : base === '/' ? `/${locale}` : `/${locale}${base}`;
  return localized === '/' ? '/' : `${localized.replace(/\/+$/, '')}/`;
}
function before(locale, href) {
  if (!href || external.some(prefix => href.startsWith(prefix)) || !href.startsWith('/')) return href;
  if (href.startsWith('/examples/')) return href;
  return localizePathname(locale, href);
}
function after(locale, href) {
  if (!href || external.some(prefix => href.startsWith(prefix)) || !href.startsWith('/')) return href;
  if (href.startsWith('/examples/') || href.startsWith('/images/')) return href;
  return localizePathname(locale, href);
}
const cases = [
  ['/images/editorial/mobile-guides/iphone-chat-mode.png', 'shared image'],
  ['/images/editorial/1-10/follow-up-en.png?size=original#image', 'image query and fragment'],
  ['/examples/read-only-prompt.txt', 'shared example'],
  ['https://code.claude.com/docs/en/remote-control', 'external URL'],
  ['#first-request', 'page fragment'],
  ['/docs/getting-started/', 'localized document'],
];
const results = Object.entries({ before, after }).map(([version, fn]) => {
  const checks = locales.flatMap(locale => cases.map(([input, kind]) => {
    const expected = kind === 'localized document' && locale !== 'en' ? `/${locale}${input}` : input;
    const actual = fn(locale, input);
    return { locale, kind, input, expected, actual, pass: actual === expected };
  }));
  return { version, passed: checks.filter(c => c.pass).length, failed: checks.filter(c => !c.pass).length, checks };
});
assert.equal(results[0].failed, 16, 'The original bug must remain reproducible');
assert.equal(results[1].failed, 0, 'The repaired policy must satisfy the cases');
for (const result of results) console.log(`${result.version}: ${result.passed} passed, ${result.failed} failed`);
if (process.argv.includes('--json')) console.log(JSON.stringify(results, null, 2));
