import map from "./legacy-image-map.json";

const LEGACY_MAP = map as Record<string, string>;

const LEGACY_HOSTS = [
  "https://www.avbeat.com",
  "https://avbeat.com",
  "http://www.avbeat.com",
  "http://avbeat.com",
];

export function rewriteLegacyImageUrl(url: string | null | undefined): string {
  if (!url) return "";
  // Direct map hit (canonical https://www.avbeat.com/...)
  const direct = LEGACY_MAP[url];
  if (direct) return direct;
  // Try alternate-host normalization
  for (const host of LEGACY_HOSTS) {
    if (url.startsWith(host)) {
      const path = url.slice(host.length);
      const canonical = `https://www.avbeat.com${path}`;
      const hit = LEGACY_MAP[canonical];
      if (hit) return hit;
    }
  }
  return url;
}

export function rewriteLegacyImageUrlsInHtml(html: string): string {
  let out = html.replace(
    /(https?:\/\/(?:www\.)?avbeat\.com\/wp-content\/uploads\/[^"'\s)]+)/g,
    (m) => rewriteLegacyImageUrl(m),
  );
  // Rewrite raw Supabase Storage URLs to clean first-party /img/<bucket>/<path>
  // so article HTML never leaks the long supabase.onsethost.com URL. Better for
  // SEO and keeps images visually first-party. Served by /img/[...path]/route.ts.
  out = out.replace(
    /https?:\/\/(?:[\w-]+\.)*supabase\.onsethost\.com\/storage\/v1\/object\/public\/([^\s"')]+)/g,
    (_m, p) => `/img/${p}`,
  );
  return out;
}

/**
 * Strip <img>, <picture>, and their wrapping <figure>/<a> tags whose src
 * still points at the dead WP host AFTER rewriteLegacyImageUrl ran. These
 * load 404s in the browser and hurt SEO; better to remove than to leave
 * broken image icons. Tags whose src is anything else are left alone.
 */
export function stripDeadLegacyImages(html: string): string {
  if (!html) return html;

  // Match <img> tags whose src still hits the dead WP host.
  const DEAD_HOST_RE = /https?:\/\/(?:www\.)?avbeat\.com\/wp-content\/uploads\//i;

  // Drop entire <figure>...</figure> blocks whose only inner content is a
  // dead-image <img>. Preserves figures that wrap working images.
  let out = html.replace(/<figure\b[^>]*>([\s\S]*?)<\/figure>/gi, (full, inner) => {
    if (!/<img\b[^>]*\bsrc\s*=\s*["'][^"']*avbeat\.com\/wp-content\/uploads\/[^"']*["']/i.test(inner)) return full;
    // figure contains a dead image — drop entirely
    return "";
  });

  // Drop <a>…<img dead …>…</a> wrappers
  out = out.replace(/<a\b[^>]*>\s*<img\b[^>]*\bsrc\s*=\s*["'][^"']*avbeat\.com\/wp-content\/uploads\/[^"']*["'][^>]*\/?>\s*<\/a>/gi, "");

  // Drop bare <img dead …>
  out = out.replace(/<img\b[^>]*\bsrc\s*=\s*["'][^"']*avbeat\.com\/wp-content\/uploads\/[^"']*["'][^>]*\/?>/gi, "");

  // Drop empty <figure></figure> left over after image removal.
  out = out.replace(/<figure\b[^>]*>\s*(?:<figcaption\b[^>]*>\s*<\/figcaption>\s*)?<\/figure>/gi, "");

  return out;
}

/** One-call helper: rewrite mapped URLs, then strip anything still dead. */
export function cleanLegacyImages(html: string): string {
  return stripDeadLegacyImages(rewriteLegacyImageUrlsInHtml(html));
}
