import * as fs from "fs";
import * as path from "path";

/**
 * Debug script to test Hapag Lloyd cookies and understand why they're not working
 */

// Helper function to load cookies from .env.hapag-cookies
function loadHapagCookies(): Record<string, string> {
  const cookiesPath = path.resolve(process.cwd(), ".env.hapag-cookies");
  const cookies: Record<string, string> = {};

  try {
    if (fs.existsSync(cookiesPath)) {
      const content = fs.readFileSync(cookiesPath, "utf-8");
      const lines = content.split("\n");
      
      for (const line of lines) {
        const trimmed = line.trim();
        if (trimmed && !trimmed.startsWith("#")) {
          const [key, ...valueParts] = trimmed.split("=");
          if (key && valueParts.length > 0) {
            cookies[key] = valueParts.join("=");
          }
        }
      }
      console.log(`✅ Loaded ${Object.keys(cookies).length} cookies from .env.hapag-cookies\n`);
    } else {
      console.log(`❌ .env.hapag-cookies file not found`);
    }
  } catch (e) {
    console.log(`❌ Error loading cookies: ${(e as any).message}`);
  }

  return cookies;
}

async function main() {
  let puppeteerExtra: any = null;

  try {
    puppeteerExtra = require("puppeteer-extra");
    const StealthPlugin = require("puppeteer-extra-plugin-stealth");
    if (StealthPlugin) {
      puppeteerExtra.use(StealthPlugin());
    }
    console.log("[Puppeteer] ✅ Loaded with Stealth plugin\n");
  } catch (e) {
    console.error("[Puppeteer] ❌ Failed to load");
    process.exit(1);
  }

  const hapagCookies = loadHapagCookies();

  try {
    const browser = await puppeteerExtra.launch({
      headless: true,
      args: [
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-dev-shm-usage",
        "--disable-gpu",
        "--disable-blink-features=AutomationControlled",
        "--window-size=1920,1080",
      ],
    });

    const page = await browser.newPage();
    await page.setViewport({ width: 1920, height: 1080 });

    // Set realistic user agent
    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("🔍 Testing Cookie Domains:\n");

    // Test different domain variations
    const domainTests = [
      { domain: ".hapag-lloyd.com", name: ".hapag-lloyd.com (wildcard)" },
      { domain: "hapag-lloyd.com", name: "hapag-lloyd.com (no dot)" },
      { domain: "www.hapag-lloyd.com", name: "www.hapag-lloyd.com (www subdomain)" },
    ];

    for (const domainTest of domainTests) {
      console.log(`\n📌 Testing domain: ${domainTest.name}`);
      
      const testCookies = [
        {
          name: "cf_clearance",
          value: hapagCookies.CF_CLEARANCE || "",
          domain: domainTest.domain,
          path: "/",
          httpOnly: true,
          secure: true,
        },
      ];

      try {
        if (hapagCookies.CF_CLEARANCE) {
          await page.setCookie(...testCookies);
          console.log(`   ✅ Cookie set successfully`);
        } else {
          console.log(`   ⚠️ No CF_CLEARANCE value to set`);
        }
      } catch (e) {
        console.log(`   ❌ Error setting cookie: ${(e as any).message}`);
      }

      // Get cookies from page
      const setCookies = await page.cookies();
      const cfClears = setCookies.filter(c => c.name === "cf_clearance");
      console.log(`   📦 Cookies on page: ${setCookies.length} total, ${cfClears.length} cf_clearance`);
      if (cfClears.length > 0) {
        const cf = cfClears[0];
        console.log(`      - Domain: ${cf.domain}`);
        console.log(`      - Path: ${cf.path}`);
        console.log(`      - Secure: ${cf.secure}`);
        console.log(`      - HttpOnly: ${cf.httpOnly}`);
        console.log(`      - Value length: ${cf.value.length} chars`);
      }

      // Clear cookies for next test
      await page.deleteCookie(...setCookies);
    }

    // Now test actual navigation with ALL cookies
    console.log(`\n\n🚀 Testing Full Navigation with All Cookies:\n`);

    const fullCookies = [
      {
        name: "cf_clearance",
        value: hapagCookies.CF_CLEARANCE || "",
        domain: ".hapag-lloyd.com",
        path: "/",
        httpOnly: true,
        secure: true,
      },
      {
        name: "JSESSIONID",
        value: hapagCookies.JSESSIONID || "",
        domain: ".hapag-lloyd.com",
        path: "/",
        httpOnly: true,
        secure: true,
      },
      {
        name: "OptanonConsent",
        value: hapagCookies.OPTANON_CONSENT || "",
        domain: ".hapag-lloyd.com",
        path: "/",
      },
      {
        name: "CF_BM",
        value: hapagCookies.CF_BM || "",
        domain: ".hapag-lloyd.com",
        path: "/",
      },
      {
        name: "CF_UVID",
        value: hapagCookies.CF_UVID || "",
        domain: ".hapag-lloyd.com",
        path: "/",
      },
    ];

    const validCookies = fullCookies.filter(c => c.value && c.value.length > 0);
    console.log(`Setting ${validCookies.length} cookies...`);
    
    try {
      await page.setCookie(...validCookies);
      console.log("✅ All cookies set\n");
    } catch (e) {
      console.log(`⚠️ Error: ${(e as any).message}\n`);
    }

    // Intercept requests to see what headers are being sent
    console.log("📡 Intercepting requests to check headers...\n");
    
    page.on("request", (req) => {
      if (req.url().includes("hapag-lloyd.com")) {
        const headers = req.headers();
        const resourceType = req.resourceType();
        
        // Only log first few requests
        if (resourceType === "document" || resourceType === "xhr") {
          console.log(`  ${resourceType.toUpperCase()}: ${req.url()}`);
          console.log(`    User-Agent: ${headers["user-agent"]?.substring(0, 60)}...`);
          console.log(`    Cookie header: ${headers["cookie"]?.substring(0, 60)}...`);
        }
      }
    });

    const url = "https://www.hapag-lloyd.com/en/online-business/track/track-by-container-solution.html?container=HLBU++6221765";
    console.log(`Navigating to: ${url}\n`);

    try {
      await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 });
      console.log("✅ Page loaded\n");

      // Wait for rendering
      await new Promise(resolve => setTimeout(resolve, 5000));

      // Check if we got Cloudflare challenge
      const html = await page.content();
      if (html.includes("Just a moment") || html.includes("cf_challenge")) {
        console.log("❌ PROBLEM: Got Cloudflare challenge page!");
        console.log("   This means cookies are NOT valid or NOT being sent correctly");
      } else if (html.includes("hl-tbl") || html.includes("hal-table")) {
        console.log("✅ SUCCESS: Got tracking page with tables!");
      } else {
        console.log("⚠️ UNCLEAR: Page loaded but no recognizable content");
        console.log(`   HTML size: ${html.length} bytes`);
      }

      // Show page title
      const title = await page.title();
      console.log(`\nPage Title: "${title}"`);

      // Check if table exists
      const tableExists = await page.evaluate(() => {
        return document.querySelector("table.hl-tbl.data.hal-table") !== null;
      });
      console.log(`Table Found: ${tableExists ? "✅ YES" : "❌ NO"}`);

    } catch (e) {
      console.log(`❌ Navigation error: ${(e as any).message}`);
    }

    await browser.close();
    console.log("\n✅ Debug complete");

  } catch (e) {
    console.error(`❌ Error: ${(e as any).message}`);
  }
}

main().catch(console.error);
