export interface AmpDetectionResult {
  hasAmpVersion: boolean;
  ampUrl: string | null;
  ampValid: boolean | null;
}

const AMP_FETCH_TIMEOUT_MS = 8000;

export async function detectAmpStatus(domHtml: string, brandUrl: string): Promise<AmpDetectionResult> {
  // Check for <link rel="amphtml" href="...">
  const ampLinkMatch = domHtml.match(/<link[^>]+rel=["']amphtml["'][^>]*>/i)
    ?? domHtml.match(/<link[^>]+href=["']([^"']*)["'][^>]+rel=["']amphtml["'][^>]*>/i);

  if (!ampLinkMatch) {
    // Check if the page itself is AMP (has <html amp> or <html ⚡>)
    const isSelfAmp = /<html[^>]+(?:amp|⚡)/i.test(domHtml);
    if (isSelfAmp) {
      return { hasAmpVersion: true, ampUrl: brandUrl, ampValid: true };
    }
    return { hasAmpVersion: false, ampUrl: null, ampValid: null };
  }

  const hrefMatch = ampLinkMatch[0].match(/href=["']([^"']*)["']/i);
  const ampUrl = hrefMatch ? resolveUrl(hrefMatch[1], brandUrl) : null;

  if (!ampUrl) {
    return { hasAmpVersion: true, ampUrl: null, ampValid: null };
  }

  // Probe the AMP URL to confirm it resolves and contains AMP markup
  try {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), AMP_FETCH_TIMEOUT_MS);
    const res = await fetch(ampUrl, {
      method: "GET",
      signal: controller.signal,
      headers: { "User-Agent": "Mozilla/5.0 (compatible; audit-bot/1.0)" },
    });
    clearTimeout(timer);

    if (!res.ok) return { hasAmpVersion: true, ampUrl, ampValid: false };

    const html = await res.text();
    const ampValid = /<html[^>]+(?:amp|⚡)/i.test(html);
    return { hasAmpVersion: true, ampUrl, ampValid };
  } catch {
    return { hasAmpVersion: true, ampUrl, ampValid: null };
  }
}

function resolveUrl(href: string, base: string): string {
  try {
    return new URL(href, base).href;
  } catch {
    return href;
  }
}
