import * as dotenv from "dotenv";
import * as path from "path";

dotenv.config({ path: path.resolve(process.cwd(), ".env") });

import puppeteerExtra from "puppeteer-extra";
import StealthPlugin from "puppeteer-extra-plugin-stealth";
import * as fs from "fs";

puppeteerExtra.use(StealthPlugin());

/**
 * Debug script to save actual CMA page HTML to file
 */

async function saveCMAPageHTML() {
  try {
    console.log("📄 Saving CMA CGM detail page HTML to file...\n");

    const trackingUrl =
      "https://www.cma-cgm.com/ebusiness/tracking/detail/CMAU0863618?SearchCriteria=BL&SearchByReference=MUC0137256";

    const browser = await puppeteerExtra.launch({
      headless: true,
      args: ["--no-sandbox", "--disable-setuid-sandbox"],
    });

    const page = await browser.newPage();

    await page.setUserAgent(
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
    );

    console.log("🌐 Loading page...");
    await page.goto(trackingUrl, {
      waitUntil: "networkidle2",
      timeout: 30000,
    });

    console.log("⏳ Waiting 10 seconds for dynamic content...");
    await new Promise(resolve => setTimeout(resolve, 10000));

    const html = await page.content();
    const outFile = "/tmp/cma-actual-page.html";
    
    fs.writeFileSync(outFile, html);
    console.log(`\n✅ HTML saved to: ${outFile}`);
    console.log(`📊 Size: ${(html.length / 1024).toFixed(2)} KB\n`);

    // Also log what we can find
    const pageInfo = await page.evaluate(() => {
      const info: any = {};
      
      info.arrivalItems = document.querySelectorAll("li.timeline--item.arrival").length;
      info.timelineItems = document.querySelectorAll("li[class*='timeline'][class*='item']").length;
      info.etaDivs = document.querySelectorAll("[class*='timeline'][class*='eta']").length;
      
      // Look for APR
      const bodyText = document.body.innerText;
      const aprs = (bodyText.match(/APR|Apr|apr/g) || []).length;
      const dates = bodyText.match(/\d{1,2}-\w{3}-\d{4}/gi) || [];
      
      info.aprCount = aprs;
      info.datesFound = dates;
      
      // Get some timeline HTML
      const firstTimeline = document.querySelector("li.timeline--item");
      if (firstTimeline) {
        info.firstTimelineHTML = firstTimeline.outerHTML.substring(0, 300);
      }
      
      return info;
    });

    console.log("🔍 Page Analysis:");
    console.log(`  Arrival items: ${pageInfo.arrivalItems}`);
    console.log(`  Timeline items: ${pageInfo.timelineItems}`);
    console.log(`  ETA divs: ${pageInfo.etaDivs}`);
    console.log(`  APR occurrences: ${pageInfo.aprCount}`);
    console.log(`  Dates found: ${pageInfo.datesFound.join(", ") || "none"}`);
    
    if (pageInfo.firstTimelineHTML) {
      console.log(`\n📋 First Timeline HTML:\n${pageInfo.firstTimelineHTML}...\n`);
    }

    await browser.close();
  } catch (error) {
    console.error("❌ Error:", error);
  }
}

saveCMAPageHTML();
