import puppeteer from "puppeteer";
import * as fs from "fs";

/**
 * Improved Puppeteer scraper with better timeout handling and debugging
 */

async function scrapeMaerskWithPuppeteer() {
  const containerId = "MNBU4288732";
  const trackingUrl = `https://www.maersk.com/tracking/${containerId}`;

  console.log("╔═══════════════════════════════════════════════════╗");
  console.log("║    Maersk Scraper with Puppeteer (Improved)      ║");
  console.log("╚═══════════════════════════════════════════════════╝\n");

  let browser;

  try {
    console.log("🚀 Launching browser (this may take a moment)...");
    browser = await puppeteer.launch({
      headless: true,
      args: [
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-blink-features=AutomationControlled",
        "--disable-dev-shm-usage",
      ],
    });

    const page = await browser.newPage();
    
    // Set viewport and user agent
    await page.setViewport({ width: 1920, height: 1080 });
    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(`📄 Navigating to: ${trackingUrl}`);
    console.log("   (Waiting for page to load - this may take 30-60 seconds...)\n");

    try {
      // Try to navigate with a longer timeout
      await page.goto(trackingUrl, {
        waitUntil: "domcontentloaded",
        timeout: 60000, // 60 second timeout
      });

      console.log("✅ Page loaded");

      // Wait a bit for dynamic content
      console.log("⏳ Waiting for tracking data to render...");
      await new Promise(resolve => setTimeout(resolve, 5000));

      // Try to find tracking elements
      console.log("🔍 Looking for tracking data...");

      // First, just get a quick peek at what's on the page
      const pageTitle = await page.title();
      console.log(`   Page title: ${pageTitle}`);

      // Check what's visible
      const bodyText = await page.evaluate(() => document.body.innerText);
      const hasTrackingContent =
        bodyText.includes("MNBU") ||
        bodyText.includes("tracking") ||
        bodyText.includes("May") ||
        bodyText.includes("arrival");

      console.log(`   Body text length: ${bodyText.length} characters`);
      console.log(`   Has tracking content: ${hasTrackingContent ? "✅" : "❌"}\n`);

      // Save HTML
      const html = await page.content();
      fs.writeFileSync("maersk-puppeteer-result.html", html);
      console.log("💾 Saved HTML to maersk-puppeteer-result.html");

      // Save screenshot
      await page.screenshot({ path: "maersk-puppeteer-result.png" });
      console.log("📸 Saved screenshot to maersk-puppeteer-result.png\n");

      // Try to extract ETA
      console.log("🔎 Analyzing page content...\n");

      const checks = [
        { name: "Contains 'MNBU4288732'", test: html.includes("MNBU4288732") },
        { name: "Contains 'milestone-date'", test: html.includes("milestone-date") },
        { name: "Contains 'Feeder arrival'", test: html.includes("Feeder arrival") },
        { name: "Contains 'Vessel arrival'", test: html.includes("Vessel arrival") },
        { name: "Contains 'May'", test: html.includes("May") },
      ];

      checks.forEach(check => {
        const status = check.test ? "✅" : "❌";
        console.log(`  ${status} ${check.name}`);
      });

      // Try to extract using Puppeteer evaluation
      console.log("\n🔍 Trying to extract ETA via JavaScript...\n");

      const etas = await page.evaluate(() => {
        // Try different selectors
        const milestones = document.querySelectorAll('[data-test="milestone-date"]');
        return Array.from(milestones).map(m => m.textContent);
      });

      if (etas.length > 0) {
        console.log(`✅ Found ${etas.length} milestone dates:`);
        etas.forEach((eta, i) => {
          console.log(`  ${i + 1}. ${eta}`);
        });
      } else {
        console.log(`❌ No milestone dates found`);

        // Try to find any date-like text
        const allText = await page.evaluate(() => {
          const text = document.body.innerText;
          // Find patterns like "31 May" or "May 31"
          const datePattern = /\d{1,2}\s+\w+\s+\d{4}|\w+\s+\d{1,2},?\s+\d{4}/g;
          return text.match(datePattern) || [];
        });

        if (allText.length > 0) {
          console.log(`\nFound date patterns:`);
          allText.slice(0, 10).forEach(date => {
            console.log(`  - ${date}`);
          });
        }
      }

    } catch (navigationError) {
      console.log(`\n⚠️  Navigation error: ${navigationError instanceof Error ? navigationError.message : navigationError}`);
      console.log("     Still saving page content for inspection...");

      const html = await page.content();
      fs.writeFileSync("maersk-puppeteer-partial.html", html);
      console.log("     Saved partial HTML to maersk-puppeteer-partial.html");
    }

    await page.close();

  } catch (error) {
    console.error(`\n❌ Error: ${error instanceof Error ? error.message : error}`);
  } finally {
    if (browser) {
      await browser.close();
      console.log("\n🔌 Browser closed");
    }
  }
}

scrapeMaerskWithPuppeteer();
