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

puppeteer.use(StealthPlugin());

async function testEvergreenScraping() {
  console.log("\n🧪 Testing Evergreen Scraping...\n");

  const containerNumber = "EMCU5515710";
  const url = "https://ct.shipmentlink.com/servlet/TDB1_CargoTracking.do";

  console.log(`📍 Container: ${containerNumber}`);
  console.log(`🔗 URL: ${url}\n`);

  let browser;

  try {
    browser = await puppeteer.launch({
      headless: true,
      args: [
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-blink-features=AutomationControlled",
      ],
    });

    const page = await browser.newPage();
    page.setDefaultNavigationTimeout(120000);

    // Set realistic headers
    await page.setUserAgent(
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    );
    await page.setViewport({ width: 1920, height: 1080 });

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

    console.log("⏳ Waiting for form to load...");
    await new Promise((resolve) => setTimeout(resolve, 2000));

    // Step 1: Select "Container No." radio button
    const containerRadio = await page.$("#s_cntr");
    if (containerRadio) {
      await containerRadio.evaluate((el: any) => el.checked = true);
      console.log("✅ Selected 'Container No.' option");
    }

    // Step 2: Fill the container number field
    console.log(`📝 Entering container number: ${containerNumber}`);
    const input = await page.$("#NO");
    if (input) {
      await input.type(containerNumber, { delay: 50 });
      console.log("✅ Entered container number");
    }

    // Step 3: Press Enter to search
    console.log("⏳ Pressing Enter to search...");
    await page.keyboard.press("Enter");

    // Wait for results
    console.log("⏳ Waiting for results (15 seconds)...");
    await new Promise((resolve) => setTimeout(resolve, 15000));

    const html = await page.content();
    fs.writeFileSync("evergreen-page.html", html);
    console.log("✅ Page loaded successfully");
    console.log("📄 HTML saved to: evergreen-page.html\n");

    // Extract date
    console.log("🔍 Extracting date...");
    const dateRegex = /<td[^>]*class="[^"]*#f12rown1[^"]*"[^>]*>[^<]*<\/td>\s*<td[^>]*class="[^"]*#f12rown1[^"]*"[^>]*>[^<]*<\/td>\s*<td[^>]*class="[^"]*#f12rown1[^"]*"[^>]*>([A-Z]{3}-\d{2}-\d{4})<\/td>/;
    const match = html.match(dateRegex);

    if (match) {
      const dateStr = match[1]; // e.g., "APR-30-2026"
      const [month, day, year] = dateStr.split("-");
      
      // Convert month
      const monthMap: { [key: string]: string } = {
        JAN: "01", FEB: "02", MAR: "03", APR: "04", MAY: "05", JUN: "06",
        JUL: "07", AUG: "08", SEP: "09", OCT: "10", NOV: "11", DEC: "12",
      };
      
      const formattedDate = `${year}-${monthMap[month]}-${day}`;
      console.log(`✅ Date found: ${dateStr} → ${formattedDate}\n`);
    } else {
      console.log("❌ Could not extract date\n");
    }

    await browser.close();
  } catch (error) {
    console.error("Error:", error instanceof Error ? error.message : error);
    if (browser) await browser.close();
  }
}

testEvergreenScraping();
