# Resort Comparison Script - Pre-loaded Test Data
# Run this with: .\compare-resorts-test.ps1

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

# Pre-loaded test resorts
$resorts = @(
    "Bahia Principe Luxury Sian Ka'an",
    "Catalonia Royal Tulum",
    "Secrets Akumal Riviera Maya",
    "UNICO 20°87° Hotel Riviera Maya",
    "TRS Yucatán Hotel",
    "Barcelo Maya Riviera",
    "Valentin Imperial Riviera Maya",
    "Grand Sirenis Riviera Maya",
    "Dreams Tulum Resort & Spa",
    "Hyatt Zilara Cap Cana",
    "Secrets Cap Cana",
    "Dreams Onyx Resort & Spa",
    "Royalton CHIC Punta Cana",
    "Iberostar Grand Bávaro"
)

Write-Host "Testing with $($resorts.Count) pre-loaded resorts:" -ForegroundColor Green
foreach ($resort in $resorts) {
    Write-Host "  • $resort" -ForegroundColor Gray
}
Write-Host ""

# Pre-set travel details
$origin = "YOW"
$departureDate = "2026-01-15"
$tripLength = 7

Write-Host "Travel Details (pre-configured):" -ForegroundColor Yellow
Write-Host "  From: $origin (Ottawa)" -ForegroundColor White
Write-Host "  Departure: $departureDate" -ForegroundColor White
Write-Host "  Trip Length: $tripLength nights`n" -ForegroundColor White

# Ask for budget
Write-Host "Budget (optional):" -ForegroundColor Yellow
$budgetInput = Read-Host "Total budget per person in CAD (or press Enter to skip)"
$budget = if ($budgetInput -eq "") { $null } else { [int]$budgetInput }

$contingency = 15
if ($budget) {
    Write-Host "Budget contingency for high-scoring resorts:" -ForegroundColor Yellow
    $contingencyInput = Read-Host "Allow % over budget for excellent matches (default: 15)"
    $contingency = if ($contingencyInput -eq "") { 15 } else { [int]$contingencyInput }
    Write-Host "  Budget: $([char]0x0024)$budget CAD" -ForegroundColor Green
    Write-Host "  Contingency: $contingency% (+$([char]0x0024)$([int]($budget * $contingency / 100)))" -ForegroundColor Green
    Write-Host "  Max budget: $([char]0x0024)$($budget + [int]($budget * $contingency / 100)) CAD`n" -ForegroundColor Cyan
}

# Ask for preferences
Write-Host "Rate your feature preferences (0-10):" -ForegroundColor Yellow
Write-Host "Press Enter to use default values`n" -ForegroundColor Gray

$preferences = @{}

$beachInput = Read-Host "Beach importance (0-10, default: 10)"
$preferences.beach = if ($beachInput -eq "") { 10 } else { [int]$beachInput }

$poolInput = Read-Host "Pool importance (0-10, default: 8)"
$preferences.pool = if ($poolInput -eq "") { 8 } else { [int]$poolInput }

$golfInput = Read-Host "Golf importance (0-10, default: 5)"
$preferences.golf = if ($golfInput -eq "") { 5 } else { [int]$golfInput }

$spaInput = Read-Host "Spa importance (0-10, default: 8)"
$preferences.spa = if ($spaInput -eq "") { 8 } else { [int]$spaInput }

$foodInput = Read-Host "Food importance (0-10, default: 9)"
$preferences.food = if ($foodInput -eq "") { 9 } else { [int]$foodInput }

$nightlifeInput = Read-Host "Nightlife importance (0-10, default: 7)"
$preferences.nightlife = if ($nightlifeInput -eq "") { 7 } else { [int]$nightlifeInput }

Write-Host "`nYour preferences:" -ForegroundColor Yellow
$preferences.GetEnumerator() | ForEach-Object {
    $bar = "█" * $_.Value
    Write-Host "  $($_.Key): $bar $($_.Value)/10" -ForegroundColor Green
}

# Build request
$requestData = @{
    resorts = $resorts
    departureDate = $departureDate
    origin = $origin
    tripLength = $tripLength
    preferences = $preferences
}

if ($budget) {
    $requestData.budget = $budget
    $requestData.contingencyPercent = $contingency
}

$requestData = $requestData | 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 "   ✓ Analysis Complete!" -ForegroundColor Green
    Write-Host "========================================`n" -ForegroundColor Cyan
    
    Write-Host "Flights from $origin on $departureDate (returning $($response.flightInfo.returnDate))`n" -ForegroundColor White
    
    if ($response.budgetInfo) {
        Write-Host "💰 Budget Analysis:" -ForegroundColor Yellow
        Write-Host "  Your Budget: $([char]0x0024)$($response.budgetInfo.budget) CAD" -ForegroundColor White
        Write-Host "  Contingency: $($response.budgetInfo.contingencyPercent)% (+$([char]0x0024)$([int]$response.budgetInfo.contingencyAmount))" -ForegroundColor Gray
        Write-Host "  Max Allowed: $([char]0x0024)$([int]$response.budgetInfo.maxBudget) CAD" -ForegroundColor Cyan
        Write-Host "  Within Budget: $($response.budgetInfo.withinBudgetCount) of $($response.budgetInfo.totalCount) resorts" -ForegroundColor Green
        if ($response.budgetInfo.overBudgetCount -gt 0) {
            Write-Host "  Over Budget: $($response.budgetInfo.overBudgetCount) resorts excluded" -ForegroundColor Red
        }
        Write-Host ""
    }
    
    if ($response.notFound.Count -gt 0) {
        Write-Host "⚠️  Resorts not in database:" -ForegroundColor Yellow
        foreach ($notFound in $response.notFound) {
            Write-Host "  - $notFound" -ForegroundColor Gray
        }
        Write-Host ""
    }
    
    # Top 3 detailed view
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "   🏆 TOP 3 RESORTS FOR YOU" -ForegroundColor Cyan
    Write-Host "========================================`n" -ForegroundColor Cyan
    
    $top3 = $response.comparisons | Select-Object -First 3
    $medal = @("🥇", "🥈", "🥉")
    
    for ($i = 0; $i -lt [Math]::Min(3, $top3.Count); $i++) {
        $comp = $top3[$i]
        $resort = $comp.resort
        
        Write-Host "$($medal[$i]) #$($i+1): " -NoNewline -ForegroundColor Yellow
        Write-Host $resort.name -ForegroundColor White
        Write-Host "    📍 $($resort.destination), $($resort.country)" -ForegroundColor Gray
        
        if ($resort.tripAdvisorRating) {
            $stars = "⭐" * [Math]::Floor($resort.tripAdvisorRating)
            Write-Host "    $stars $($resort.tripAdvisorRating)/5.0 ($($resort.tripAdvisorReviews) reviews)" -ForegroundColor Yellow
        }
        
        Write-Host "    💰 Resort: $($resort.priceRange) | ✈️  Flights: $($comp.estimatedFlightPrice)" -ForegroundColor Cyan
        
        if ($comp.estimatedTotalMin) {
            $totalRange = "$([char]0x0024)$([int]$comp.estimatedTotalMin)-$([char]0x0024)$([int]$comp.estimatedTotalMax)"
            Write-Host "    💵 Total Estimate: $totalRange" -ForegroundColor Green
        }
        
        if ($comp.budgetStatus) {
            $statusColor = if ($comp.withinBudget) { "Green" } else { "Red" }
            Write-Host "    📊 Budget: $($comp.budgetStatus)" -ForegroundColor $statusColor
        }
        
        Write-Host "    🎯 Match Score: $($comp.matchScore)/1000" -ForegroundColor Green
        
        Write-Host "    Best Features:" -ForegroundColor Gray
        $topFeatures = $resort.features.GetEnumerator() | Sort-Object Value -Descending | Select-Object -First 3
        foreach ($feature in $topFeatures) {
            Write-Host "      • $($feature.Key): $($feature.Value)/10" -ForegroundColor White
        }
        
        Write-Host "    🔗 Flights: " -NoNewline -ForegroundColor Gray
        Write-Host $comp.flightLinks.skyscanner -ForegroundColor Blue
        Write-Host ""
    }
    
    # Full comparison table
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "   📊 FULL COMPARISON TABLE" -ForegroundColor Cyan
    Write-Host "========================================`n" -ForegroundColor Cyan
    
    $tableData = @()
    foreach ($comp in $response.comparisons) {
        $r = $comp.resort
        $tableData += [PSCustomObject]@{
            "#" = $response.comparisons.IndexOf($comp) + 1
            Resort = $r.name.Substring(0, [Math]::Min(25, $r.name.Length))
            Dest = $r.destination.Substring(0, [Math]::Min(15, $r.destination.Length))
            Rating = "$($r.tripAdvisorRating)/5"
            Reviews = $r.tripAdvisorReviews
            Price = $r.priceRange
            Beach = $r.features.beach
            Pool = $r.features.pool
            Spa = $r.features.spa
            Food = $r.features.food
            Score = $comp.matchScore
        }
    }
    
    $tableData | Format-Table -AutoSize
    
    # Feature breakdown by resort
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "   📈 DETAILED FEATURE BREAKDOWN" -ForegroundColor Cyan
    Write-Host "========================================`n" -ForegroundColor Cyan
    
    foreach ($comp in $response.comparisons) {
        $r = $comp.resort
        Write-Host "$($r.name)" -ForegroundColor White
        Write-Host "  Beach:$($r.features.beach) Pool:$($r.features.pool) Golf:$($r.features.golf) Spa:$($r.features.spa) Food:$($r.features.food) Nightlife:$($r.features.nightlife) Culture:$($r.features.culture) Outdoor:$($r.features.outdoor) Family:$($r.features.family)" -ForegroundColor Gray
    }
    
    Write-Host ""
    
    # Export
    Write-Host "========================================" -ForegroundColor Cyan
    $export = Read-Host "Export 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
                DepartureDate = $departureDate
                ReturnDate = $response.flightInfo.returnDate
                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_test_$(Get-Date -Format 'yyyy-MM-dd_HHmmss').csv"
        $exportData | Export-Csv -Path $filename -NoTypeInformation
        Write-Host "✓ Exported to $filename" -ForegroundColor Green
    }
    
    # Open winner
    $openTop = Read-Host "Open flights for #1 resort? (y/n)"
    
    if ($openTop -eq "y") {
        $winner = $response.comparisons[0]
        Write-Host "`nOpening flights for $($winner.resort.name)..." -ForegroundColor Green
        Start-Process $winner.flightLinks.skyscanner
    }
    
    Write-Host "`n🎉 Comparison complete! Happy vacation planning! 🏖️✈️`n" -ForegroundColor Cyan
    
} catch {
    Write-Host "✗ Error:" -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
    Write-Host "`nMake sure server is running: npm run dev`n" -ForegroundColor Yellow
}
