import * as fs from "fs";
import * as path from "path";
import { extractETAFromHTML } from "@/lib/shipping-scraper";

/**
 * Demo: Extract ETA from saved HTML file
 * This is useful when the website blocks direct scraping but you have the HTML
 * 
 * Run with: npx tsx scripts/demo-extract-from-html.ts <html-file> <carrier>
 * Example: npx tsx scripts/demo-extract-from-html.ts hmm-results.html HMM
 */

async function main() {
  const args = process.argv.slice(2);

  if (args.length < 2) {
    console.log("Usage: npx tsx scripts/demo-extract-from-html.ts <html-file> <carrier>");
    console.log("\nExample with HMM:");
    console.log("  1. Copy the HTML from the browser (F12 > Inspector)");
    console.log("  2. Save it to a file (e.g., hmm-results.html)");
    console.log("  3. Run: npx tsx scripts/demo-extract-from-html.ts hmm-results.html HMM");
    console.log("\nSupported carriers: HMM, Hapag-Lloyd, CMA");
    process.exit(1);
  }

  const [htmlFile, carrier] = args;
  const filePath = path.resolve(process.cwd(), htmlFile);

  // Check if file exists
  if (!fs.existsSync(filePath)) {
    console.log(`❌ File not found: ${filePath}`);
    process.exit(1);
  }

  console.log(`📄 Reading HTML from: ${filePath}`);
  const html = fs.readFileSync(filePath, "utf-8");
  console.log(`✅ Loaded ${html.length} bytes\n`);

  // Extract ETA
  console.log(`🔍 Extracting ETA for carrier: ${carrier}\n`);
  const result = extractETAFromHTML(html, carrier);

  console.log("=== RESULT ===\n");
  console.log(`Success: ${result.success}`);
  console.log(`ETA: ${result.eta || "Not found"}`);
  console.log(`Message: ${result.message}`);

  if (result.success && result.eta) {
    console.log(`\n✅ Found ETA: ${result.eta}`);
    console.log("\nYou can now update the database with this ETA:");
    console.log(`  UPDATE container_shipment SET eta = '${result.eta}' WHERE id = '<container-id>';`);
  } else {
    console.log("\n❌ Could not extract ETA from the HTML");
    console.log("\nMake sure:");
    console.log("1. The HTML contains the tracking results (not just the search form)");
    console.log("2. The 'Discharging Port' or similar field is visible in the HTML");
    console.log("3. You've copied the full page HTML including all tables/data");
  }

  process.exit(result.success ? 0 : 1);
}

main();
