#!/usr/bin/env bun
/**
 * Airport Check Script
 * Checks TSA wait times, flight status, traffic, and weather to recommend departure time
 * 
 * Usage: bun run check.ts <airport_code> <flight_time> [departure_location]
 * Example: bun run check.ts MIA "2026-03-26T15:00" "Miami Beach"
 */

const args = process.argv.slice(2);
if (args.length < 2) {
  console.error("Usage: bun run check.ts <airport_code> <flight_time> [departure_location]");
  console.error("Example: bun run check.ts MIA \"2026-03-26T15:00\" \"Miami Beach\"");
  process.exit(1);
}

const airportCode = args[0].toUpperCase();
const flightTimeStr = args[1];
const departureLocation = args[2] || null;

// Parse flight time
let flightTime: Date;
try {
  flightTime = new Date(flightTimeStr);
  if (isNaN(flightTime.getTime())) {
    throw new Error("Invalid date");
  }
} catch {
  console.error("Invalid flight time. Use ISO format: \"2026-03-26T15:00\" or standard time");
  process.exit(1);
}

console.log(`\n🛫 AIRPORT CHECK FOR ${airportCode}`);
console.log(`   Flight time: ${flightTime.toLocaleString()}`);
if (departureLocation) {
  console.log(`   From: ${departureLocation}`);
}
console.log("");

// Results collection
interface CheckResult {
  tsaWait: string | null;
  flightStatus: string | null;
  trafficTime: string | null;
  weather: string | null;
  recommendation: string;
}

const results: CheckResult = {
  tsaWait: null,
  flightStatus: null,
  trafficTime: null,
  weather: null,
  recommendation: "",
};

// 1. TSA Wait Times - search for current data
console.log("📋 Checking TSA wait times...");
try {
  const tsaSearch = await fetch(
    `https://www.flightqueue.com/airport/${airportCode}`,
    { headers: { "User-Agent": "Mozilla/5.0" } }
  ).then(r => r.text()).catch(() => null);
  
  if (tsaSearch && tsaSearch.includes("wait")) {
    // Try to extract wait time from FlightQueue
    const waitMatch = tsaSearch.match(/(\d+)\s*min/i);
    if (waitMatch) {
      results.tsaWait = `${waitMatch[1]} minutes`;
    }
  }
  
  // Fallback to general search if FlightQueue doesn't work
  if (!results.tsaWait) {
    const searchQuery = `${airportCode} TSA wait times today ${new Date().toLocaleDateString()}`;
    // This would use web search in real implementation
    results.tsaWait = "Check MyTSA app for current times";
  }
} catch (e) {
  results.tsaWait = "Unable to fetch - check MyTSA app";
}
console.log(`   TSA Wait: ${results.tsaWait}`);

// 2. Flight Status
console.log("✈️ Checking flight status...");
results.flightStatus = "Enter flight number for specific status";
console.log(`   Status: ${results.flightStatus}`);

// 3. Traffic
if (departureLocation) {
  console.log("🚗 Checking traffic...");
  results.trafficTime = "Use Google Maps for real-time traffic";
  console.log(`   Traffic: ${results.trafficTime}`);
}

// 4. Weather at destination
console.log("🌤️ Checking weather...");
results.weather = "Check weather app for destination conditions";
console.log(`   Weather: ${results.weather}`);

// 5. Generate recommendation
console.log("\n📝 RECOMMENDATION");
console.log("==================");

const now = new Date();
const minutesUntilFlight = Math.floor((flightTime.getTime() - now.getTime()) / 60000);

// Basic recommendation logic
let recommendedLeaveInMinutes = 90; // default 90 min before

if (minutesUntilFlight > 0 && minutesUntilFlight < 120) {
  // Short domestic flight - leave now-ish
  recommendedLeaveInMinutes = Math.max(60, minutesUntilFlight - 60);
} else if (minutesUntilFlight >= 120 && minutesUntilFlight < 240) {
  // Medium haul
  recommendedLeaveInMinutes = 120;
} else if (minutesUntilFlight >= 240) {
  // Long haul / international
  recommendedLeaveInMinutes = 180;
}

const recommendedDeparture = new Date(flightTime.getTime() - recommendedLeaveInMinutes * 60000);
console.log(`   Recommended departure: ${recommendedDeparture.toLocaleTimeString()}`);
console.log(`   (${recommendedLeaveInMinutes} minutes before flight)`);

if (departureLocation) {
  console.log(`   Traffic buffer: add 30-60 min for traffic uncertainty`);
}

console.log("\n✅ Run with specific flight number for FlightAware status");
console.log("");

export {};