/// <reference types="@fastly/js-compute" />
import { getGeolocationForIpAddress } from "fastly:geolocation";
import { HTMLRewritingStream } from "fastly:html-rewriter";

async function handleRequest(event) {
  try {
    // 1. Grab geolocation data based on the visitor's IP address
    const clientIp = event.client.address;
    const geo = getGeolocationForIpAddress(clientIp);
    const city = geo?.city || "The Matrix";
    const country = geo?.country_name || "Cyberspace";

    // 2. Fetch the original, unmodified webpage from your backend/origin
    const backendResponse = await fetch("https://example.com", {
      backend: "example"
    });

    // 3. Initialize the streaming HTML rewriter
    const transformer = new HTMLRewritingStream()
      
      // Inject some terrible 90s CSS into the <head>
      .onElement("head", (el) => {
        el.append(`
          <style>
            body { 
              font-family: 'Comic Sans MS', 'Chalkboard SE', cursive !important; 
              background: linear-gradient(45deg, #ff00ff, #00ffff) !important; 
              color: #0000ff !important;
            }
            h1, h2, h3 { 
              color: #ffff00 !important; 
              background-color: #000000 !important;
              padding: 10px;
              text-align: center;
              border: 4px dashed #ff0000;
              text-transform: uppercase;
            }
          </style>
        `, { escapeHTML: false });
      })
      // Add a base href to point any relative assets appropriately
      .onElement("head", (el) => {
        el.prepend(`<base href="https://example.com/">`, { escapeHTML: false });
      })
      // Prepend a localized marquee banner to the top of the <body>
      .onElement("body", (el) => {
        el.prepend(`
          <marquee scrollamount="12" style="background: #000; color: #00ff00; font-family: monospace; font-size: 22px; padding: 12px; border-bottom: 5px solid #ff00ff; display: block;">
            ⚡ WELCOME SURFER! ⚡ REWRITING LIVE AT THE EDGE FOR A VISITOR IN ${city.toUpperCase()}, ${country.toUpperCase()}! YOU ARE THE 1,000,000th VISITOR! ⚡
          </marquee>
        `, { escapeHTML: false });
      })
      
      // Append retro emojis to all <h1> tags
      .onElement("h1", (el) => {
        el.append(" 🔥 FASTLY COMPUTE HTMLREWRITINGSTREAM ACTIVE 🔥");
      });

    // 4. Pipe the incoming backend body straight through our rewriter
    // This allows fragments to be modified and sent immediately without waiting for the full page!
    const rewrittenBody = backendResponse.body.pipeThrough(transformer);

    // 5. Return the streaming response back to the browser
    return new Response(rewrittenBody, {
      status: 200,
      headers: new Headers({
        "content-type": "text/html; charset=utf-8",
      }),
    });

  } catch (error) {
    console.error(error);
    return new Response("Internal Server Error", { status: 500 });
  }
}

addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));