# Resort Comparison Script
# Run this with: .\compare-resorts.ps1

Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "   Resort Comparison Tool" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan

# Get resort list
Write-Host "Paste your list of resorts (one per line)." -ForegroundColor Yellow
Write-Host "When finished, press Enter on an empty line.`n" -ForegroundColor Gray

$resorts = @()
$lineCount = 0

while ($true) {
    $lineCount++
    $line = Read-Host "Resort $lineCount (or press Enter to finish)"
    
    if ([string]::IsNullOrWhiteSpace($line)) {
        break
    }
    
    $resorts += $line.Trim()
}

if ($resorts.Count -eq 0) {
    Write-Host "No resorts entered. Exiting.`n" -ForegroundColor Red
    exit
}

Write-Host "`n✓ Entered $($resorts.Count) resorts`n" -ForegroundColor Green

# Travel details
Write-Host "Travel Details:" -ForegroundColor Yellow
$origin = (Read-Host "Departure city (default: YOW)").ToUpper().Trim()
if ([string]::IsNullOrWhiteSpace($origin)) { $origin = "YOW" }

$departureDate = Read-Host "Departure date (YYYY-MM-DD, default: 2026-01-15)"
if ([string]::IsNullOrWhiteSpace($departureDate)) { $departureDate = "2026-01-15" }

$tripLength = Read-Host "Trip length in nights (default: 7)"
if ([string]::IsNullOrWhiteSpace($tripLength)) { $tripLength = 7 } else { $tripLength = [int]$tripLength }

# Feature preferences
Write-Host "`nRate feature importance (0-10):" -ForegroundColor Yellow
Write-Host "Press Enter to skip a feature`n" -ForegroundColor Gray

$preferences = @{}

$beachInput = Read-Host "Beach (0-10)"
if ($beachInput -ne "") { $preferences.beach = [int]$beachInput }

$poolInput = Read-Host "Pool (0-10)"
if ($poolInput -ne "") { $preferences.pool = [int]$poolInput }

$golfInput = Read-Host "Golf (0-10)"
if ($golfInput -ne "") { $preferences.golf = [int]$golfInput }

$spaInput = Read-Host "Spa (0-10)"
if ($spaInput -ne "") { $preferences.spa = [int]$spaInput }

$foodInput = Read-Host "Food (0-10)"
if ($foodInput -ne "") { $preferences.food = [int]$foodInput }

$nightlifeInput = Read-Host "Nightlife (0-10)"
if ($nightlifeInput -ne "") { $preferences.nightlife = [int]$nightlifeInput }

# Build request
$requestData = @{
    resorts = $resorts
    departureDate = $departureDate
    origin = $origin
    tripLength = $tripLength
    preferences = $preferences
} | ConvertTo-Json -Depth 3

Write-Host "`nAnalyzing resorts and searching flights...`n" -ForegroundColor Yellow

try {
    $response = Invoke-RestMethod -Uri "http://localhost:4000/api/resort-compare" -Method POST -Body $requestData -ContentType "application/json"
    
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "   Comparison Results" -ForegroundColor Cyan
    Write-Host "========================================`n" -ForegroundColor Cyan
    
    Write-Host "Flight Details:" -ForegroundColor Yellow
    Write-Host "  From: $origin" -ForegroundColor White
    Write-Host "  Departure: $($response.flightInfo.departureDate)" -ForegroundColor White
    Write-Host "  Return: $($response.flightInfo.returnDate)" -ForegroundColor White
    Write-Host "  Duration: $($response.flightInfo.tripLength) nights`n" -ForegroundColor White
    
    if ($response.notFound.Count -gt 0) {
        Write-Host "⚠️  Resorts not found in database:" -ForegroundColor Yellow
        foreach ($notFound in $response.notFound) {
            Write-Host "  - $notFound" -ForegroundColor Gray
        }
        Write-Host ""
    }
    
    if ($response.comparisons.Count -eq 0) {
        Write-Host "No resorts found in database.`n" -ForegroundColor Red
        exit
    }
    
    # Display comparison grid
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "   Resort Rankings" -ForegroundColor Cyan
    Write-Host "========================================`n" -ForegroundColor Cyan
    
    $rank = 1
    foreach ($comp in $response.comparisons) {
        $resort = $comp.resort
        
        # Rank and name
        Write-Host "[$rank] " -NoNewline -ForegroundColor Cyan
        Write-Host $resort.name -ForegroundColor White -NoNewline
        Write-Host " (Match Score: $($comp.matchScore))" -ForegroundColor DarkGray
        
        # Location
        Write-Host "    📍 Location: " -NoNewline -ForegroundColor Gray
        Write-Host "$($resort.destination), $($resort.country) [$($resort.airportCode)]" -ForegroundColor White
        
        # TripAdvisor rating
        if ($resort.tripAdvisorRating) {
            $stars = "⭐" * [Math]::Floor($resort.tripAdvisorRating)
            Write-Host "    ⭐ TripAdvisor: " -NoNewline -ForegroundColor Gray
            Write-Host "$($resort.tripAdvisorRating)/5.0 $stars " -NoNewline -ForegroundColor Yellow
            Write-Host "($($resort.tripAdvisorReviews) reviews)" -ForegroundColor DarkGray
        }
        
        # Price range
        Write-Host "    💰 Price Range: " -NoNewline -ForegroundColor Gray
        Write-Host $resort.priceRange -ForegroundColor Green
        
        # All-inclusive
        if ($resort.allInclusive) {
            Write-Host "    ✓ All-Inclusive" -ForegroundColor Green
        }
        
        # Feature ratings (top 5)
        Write-Host "    📊 Features:" -ForegroundColor Gray
        $topFeatures = $resort.features.GetEnumerator() | Sort-Object Value -Descending | Select-Object -First 5
        foreach ($feature in $topFeatures) {
            $bar = "█" * $feature.Value
            $userPref = if ($preferences.ContainsKey($feature.Key)) { " (You rated: $($preferences[$feature.Key]))" } else { "" }
            Write-Host "       $($feature.Key): $bar $($feature.Value)/10$userPref" -ForegroundColor White
        }
        
        # Flight estimate
        Write-Host "    ✈️  Est. Flight: " -NoNewline -ForegroundColor Gray
        Write-Host $comp.estimatedFlightPrice -ForegroundColor Cyan
        
        # Flight links
        Write-Host "    🔗 Book Flights:" -ForegroundColor Gray
        Write-Host "       Skyscanner: " -NoNewline -ForegroundColor DarkGray
        Write-Host $comp.flightLinks.skyscanner -ForegroundColor Blue
        Write-Host "       Google Flights: " -NoNewline -ForegroundColor DarkGray
        Write-Host $comp.flightLinks.googleFlights -ForegroundColor Blue
        Write-Host "       Air Canada: " -NoNewline -ForegroundColor DarkGray
        Write-Host $comp.flightLinks.airCanada -ForegroundColor Blue
        
        Write-Host ""
        $rank++
    }
    
    # Summary table
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "   Quick Comparison Table" -ForegroundColor Cyan
    Write-Host "========================================`n" -ForegroundColor Cyan
    
    $tableData = @()
    foreach ($comp in $response.comparisons) {
        $tableData += [PSCustomObject]@{
            Rank = $response.comparisons.IndexOf($comp) + 1
            Resort = $comp.resort.name.Substring(0, [Math]::Min(30, $comp.resort.name.Length))
            Location = $comp.resort.destination
            Airport = $comp.resort.airportCode
            Rating = "$($comp.resort.tripAdvisorRating)/5"
            Price = $comp.resort.priceRange
            Score = $comp.matchScore
        }
    }
    
    $tableData | Format-Table -AutoSize
    
    # Export options
    Write-Host "========================================`n" -ForegroundColor Cyan
    $export = Read-Host "Export detailed comparison to CSV? (y/n)"
    
    if ($export -eq "y") {
        $exportData = @()
        foreach ($comp in $response.comparisons) {
            $resort = $comp.resort
            $exportData += [PSCustomObject]@{
                Rank = $response.comparisons.IndexOf($comp) + 1
                Resort = $resort.name
                Destination = $resort.destination
                Country = $resort.country
                Airport = $resort.airportCode
                TripAdvisorRating = $resort.tripAdvisorRating
                TripAdvisorReviews = $resort.tripAdvisorReviews
                PriceRange = $resort.priceRange
                AllInclusive = $resort.allInclusive
                MatchScore = $comp.matchScore
                Beach = $resort.features.beach
                Pool = $resort.features.pool
                Golf = $resort.features.golf
                Spa = $resort.features.spa
                Food = $resort.features.food
                Nightlife = $resort.features.nightlife
                Shopping = $resort.features.shopping
                Culture = $resort.features.culture
                Outdoor = $resort.features.outdoor
                Family = $resort.features.family
                EstFlightPrice = $comp.estimatedFlightPrice
                SkyscannerLink = $comp.flightLinks.skyscanner
                GoogleFlightsLink = $comp.flightLinks.googleFlights
                AirCanadaLink = $comp.flightLinks.airCanada
            }
        }
        
        $filename = "resort_comparison_$(Get-Date -Format 'yyyy-MM-dd_HHmmss').csv"
        $exportData | Export-Csv -Path $filename -NoTypeInformation
        Write-Host "✓ Exported to $filename" -ForegroundColor Green
    }
    
    # Open best match
    $openBest = Read-Host "Open flights for top-ranked resort in browser? (y/n)"
    
    if ($openBest -eq "y") {
        $topResort = $response.comparisons[0]
        Write-Host "Opening Skyscanner for $($topResort.resort.name)..." -ForegroundColor Green
        Start-Process $topResort.flightLinks.skyscanner
    }
    
    Write-Host "`nHappy planning! 🏖️✈️`n" -ForegroundColor Cyan
    
} catch {
    Write-Host "✗ Error comparing resorts:" -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
    Write-Host "`nMake sure the server is running on http://localhost:4000" -ForegroundColor Yellow
    Write-Host "Run: npm run dev`n" -ForegroundColor Gray
}
