import json
from pathlib import Path
import re
from types import SimpleNamespace

from django.conf import settings
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Count, F, Q
from django.http import Http404
from django.http import JsonResponse
from django.shortcuts import redirect
from django.templatetags.static import static
from django.utils import timezone
from django.urls import reverse
from django.views import View
from django.views.generic import FormView, ListView, TemplateView

from .forms import ContactEnquiryForm, CustomerReviewForm
from .models import CabService, CustomerReview, Destination, GalleryImage, HolidayPackage, VisitorCounter, WebsiteLikeCounter


GALLERY_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}
GALLERY_EXCLUDES = {
    "aarya-hero.png",
    "logo.jpeg",
    "logo-navbar.jpeg",
    "travel-placeholder.svg",
}
GALLERY_NAME_FIXES = {
    "ashmir": "kashmir",
    "butha": "bhutan",
    "buthan": "bhutan",
    "coorag": "coorg",
    "chikkamagaluru": "chikmagalur",
    "chikkamangaluru": "chikmagalur",
    "darjeeling himalayan railway": "darjeeling",
    "erorope": "europe",
    "erurope": "europe",
}
GALLERY_SPECIAL_FILES = {
    "sumit-sourav-esrtxpd9q1c-unsplash": "scenic routes",
}
GALLERY_GROUP_ORDER = [
    "cab services",
    "chikmagalur",
    "kerala",
    "goa",
    "coorg",
    "darjeeling",
    "andaman",
    "bhutan",
    "bali",
    "singapore",
    "thailand",
    "kashmir",
    "himachal",
    "europe",
    "wayanad",
    "scenic routes",
]

PACKAGE_PLACEHOLDER_IMAGE = "images/travel-placeholder.svg"
IMAGE_PATH_ALIASES = {
    "images/europe-2.jpg": "images/erurope-2.jpg",
}


def safe_static_image(path, fallback=PACKAGE_PLACEHOLDER_IMAGE):
    candidate = IMAGE_PATH_ALIASES.get(path, path)
    static_file = settings.BASE_DIR / "static" / Path(candidate)
    if static_file.exists():
        return static(candidate)
    return static(fallback)

OLD_SITE_TOUR_PRICES = [
    {
        "title": "Mauritius Tour Packages",
        "subtitle": "Island hopping, lagoons, and beach resorts",
        "duration": "5 Nights - 6 Days",
        "price": "1,15,000",
        "image": "images/mauritius-hero.jpeg",
    },
    {
        "title": "Bali Tour Package",
        "subtitle": "Kintamani, Ubud, water sports, Uluwatu, and Nusa Penida",
        "duration": "6 Nights - 7 Days",
        "price": "1,00,000",
        "image": "images/bali-11.jpg",
    },
    {
        "title": "Bangkok & Pattaya",
        "subtitle": "Culture, nightlife, beaches, and city sightseeing",
        "duration": "5 Nights - 6 Days",
        "price": "63,000",
        "image": "images/thailand-3.jpg",
    },
    {
        "title": "Singapore-Malaysia Tour",
        "subtitle": "Sentosa, Universal Studios, and Petronas Towers",
        "duration": "6 Nights - 7 Days",
        "price": "1,20,000",
        "image": "images/singapore-10.jpg",
    },
    {
        "title": "Maldives Getaway",
        "subtitle": "Overwater stays, snorkeling, and island transfers",
        "duration": "4 Nights - 5 Days",
        "price": "95,000",
        "image": "images/Maldives-hero.jpeg",
    },
    {
        "title": "Europe Grand Tour",
        "subtitle": "Paris, Switzerland, Italy, and Netherlands",
        "duration": "10 Nights - 11 Days",
        "price": "2,50,000",
        "image": "images/erurope-3.jpg",
    },
]

COMMON_PACKAGE_INCLUDES = [
    "Hotel accommodation",
    "Daily breakfast",
    "Sightseeing support",
    "Private cab",
    "Airport or railway transfers",
    "Driver allowance",
    "Toll and parking guidance",
    "Travel assistance",
]

COMMON_PACKAGE_EXCLUDES = [
    "Airfare or train fare",
    "Lunch and dinner unless specified",
    "Personal expenses",
    "Entry tickets",
    "Adventure activities",
    "Travel insurance",
    "GST if applicable",
]

DESTINATION_HIGHLIGHTS = {
    "chikmagalur-tour-package": [
        {"icon": "fa-solid fa-mountain", "title": "Mullayanagiri Peak", "description": "Trek to South India's highest peak for sweeping sunrise and valley views."},
        {"icon": "fa-solid fa-mug-hot", "title": "Coffee Plantations", "description": "Walk through aromatic estates and experience bean-to-cup coffee trails."},
        {"icon": "fa-solid fa-water", "title": "Hebbe & Jhari Falls", "description": "Explore misty waterfall routes with monsoon-fed cascades and green surrounds."},
        {"icon": "fa-solid fa-paw", "title": "Bhadra Wildlife Sanctuary", "description": "Discover rich biodiversity, forest drives, and birdwatching opportunities."},
        {"icon": "fa-solid fa-camera", "title": "Scenic Viewpoints", "description": "Capture postcard-perfect hills, clouds, and endless coffee country landscapes."},
        {"icon": "fa-solid fa-road", "title": "Adventure Drives", "description": "Enjoy winding ghat roads with dramatic bends, viewpoints, and mountain air."},
    ],
    "coorg-tour-package": [
        {"icon": "fa-solid fa-waterfall", "title": "Abbey Falls", "description": "Visit Coorg's iconic waterfall framed by spice and coffee plantation greens."},
        {"icon": "fa-solid fa-sun", "title": "Raja's Seat", "description": "Take in golden sunsets and panoramic hill views from this classic vantage point."},
        {"icon": "fa-solid fa-elephant", "title": "Dubare Elephant Camp", "description": "Experience guided interactions and riverbank walks near elephant habitats."},
        {"icon": "fa-solid fa-seedling", "title": "Coffee Estates", "description": "Stroll through lush estates and sample authentic Coorg coffee flavors."},
        {"icon": "fa-solid fa-gopuram", "title": "Golden Temple", "description": "Admire serene Tibetan architecture, prayer halls, and cultural calm."},
        {"icon": "fa-solid fa-tree", "title": "Nature Trails", "description": "Unwind on scenic trails through forests, streams, and misty hills."},
    ],
    "mysore-tour-package": [
        {"icon": "fa-solid fa-landmark", "title": "Mysore Palace", "description": "Witness royal architecture, illuminated facades, and ornate heritage halls."},
        {"icon": "fa-solid fa-mountain-city", "title": "Chamundi Hills", "description": "Visit hilltop temples and enjoy city panoramas from elevated viewpoints."},
        {"icon": "fa-solid fa-fountain", "title": "Brindavan Gardens", "description": "Enjoy musical fountains, landscaped lawns, and evening light displays."},
        {"icon": "fa-solid fa-church", "title": "St. Philomena's Church", "description": "See neo-gothic spires and detailed interiors at this iconic city church."},
        {"icon": "fa-solid fa-otter", "title": "Mysore Zoo", "description": "Explore one of India's oldest zoos with diverse wildlife enclosures."},
        {"icon": "fa-solid fa-bag-shopping", "title": "Local Shopping", "description": "Shop for sandalwood, silk, handicrafts, and famous Mysore delights."},
    ],
    "ooty-tour-package": [
        {"icon": "fa-solid fa-flower", "title": "Botanical Garden", "description": "Walk through curated floral landscapes and heritage garden sections."},
        {"icon": "fa-solid fa-ship", "title": "Ooty Lake", "description": "Relax by the lakefront with scenic boating and cool hill weather."},
        {"icon": "fa-solid fa-mountain", "title": "Doddabetta Peak", "description": "Enjoy panoramic Nilgiri views from Ooty's highest accessible summit."},
        {"icon": "fa-solid fa-train-tram", "title": "Nilgiri Mountain Railway", "description": "Ride the heritage toy train through tunnels, bridges, and valleys."},
        {"icon": "fa-solid fa-mug-hot", "title": "Tea Estates", "description": "Visit rolling tea gardens and taste fresh Nilgiri tea varieties."},
        {"icon": "fa-solid fa-tree-city", "title": "Pine Forest", "description": "Explore cinematic pine woods ideal for short walks and photography."},
    ],
    "hampi-tour-package": [
        {"icon": "fa-solid fa-place-of-worship", "title": "Virupaksha Temple", "description": "Visit Hampi's living temple complex with timeless Dravidian architecture."},
        {"icon": "fa-solid fa-chess-rook", "title": "Stone Chariot", "description": "See the world-famous monolithic chariot at the Vittala complex."},
        {"icon": "fa-solid fa-archway", "title": "Vittala Temple", "description": "Explore musical pillars and intricate carvings of Vijayanagara grandeur."},
        {"icon": "fa-solid fa-building-columns", "title": "Lotus Mahal", "description": "Admire elegant Indo-Islamic design in the royal enclosure area."},
        {"icon": "fa-solid fa-sun", "title": "Sunset Point", "description": "Watch dramatic sunset hues across Hampi's surreal boulder landscape."},
        {"icon": "fa-solid fa-life-ring", "title": "Coracle Ride", "description": "Enjoy a traditional coracle experience on the Tungabhadra river."},
    ],
    "dandeli-tour-package": [
        {"icon": "fa-solid fa-water", "title": "River Rafting", "description": "Experience thrilling white-water rafting on the lively Kali river."},
        {"icon": "fa-solid fa-binoculars", "title": "Jungle Safari", "description": "Spot wildlife and birds on guided forest safari routes."},
        {"icon": "fa-solid fa-mountain", "title": "Syntheri Rocks", "description": "Visit dramatic limestone monoliths carved by time and river flow."},
        {"icon": "fa-solid fa-cave", "title": "Kavala Caves", "description": "Trek into ancient cave formations for a raw adventure experience."},
        {"icon": "fa-solid fa-route", "title": "Zipline Adventure", "description": "Add high-adrenaline moments with safe, guided zipline activities."},
        {"icon": "fa-solid fa-campground", "title": "Nature Camping", "description": "Unplug with riverside camp stays, bonfires, and starlit evenings."},
    ],
    "kerala-tour-package": [
        {"icon": "fa-solid fa-water", "title": "Backwaters", "description": "Cruise Kerala's calm canals framed by coconut groves and village life."},
        {"icon": "fa-solid fa-ship", "title": "Houseboats", "description": "Stay aboard traditional houseboats with scenic overnight backwater views."},
        {"icon": "fa-solid fa-leaf", "title": "Tea Gardens", "description": "Walk through Munnar's rolling tea estates and mist-covered slopes."},
        {"icon": "fa-solid fa-umbrella-beach", "title": "Beaches", "description": "Unwind on golden shores with vibrant sunsets and sea breeze."},
        {"icon": "fa-solid fa-spa", "title": "Ayurveda", "description": "Rejuvenate with authentic wellness therapies and traditional treatments."},
        {"icon": "fa-solid fa-hippo", "title": "Wildlife", "description": "Explore sanctuary zones and spice forest habitats with guided visits."},
    ],
    "goa-tour-package": [
        {"icon": "fa-solid fa-umbrella-beach", "title": "Beaches", "description": "Enjoy lively shorelines, beach shacks, and relaxed coastal vibes."},
        {"icon": "fa-solid fa-person-swimming", "title": "Water Sports", "description": "Try parasailing, jet skiing, banana rides, and more seaside fun."},
        {"icon": "fa-solid fa-music", "title": "Nightlife", "description": "Experience beach clubs, live music venues, and vibrant evening scenes."},
        {"icon": "fa-solid fa-fort-awesome", "title": "Forts", "description": "Explore historic Portuguese forts with dramatic sea-facing viewpoints."},
        {"icon": "fa-solid fa-church", "title": "Churches", "description": "Visit UNESCO-era churches and old-Goa architectural landmarks."},
        {"icon": "fa-solid fa-ship", "title": "Sunset Cruises", "description": "Sail along scenic waters with music, views, and sunset skies."},
    ],
    "himachal-tour-package": [
        {"icon": "fa-solid fa-mountain", "title": "Snow Mountains", "description": "Enjoy alpine vistas, snowy ridges, and postcard-perfect mountain routes."},
        {"icon": "fa-solid fa-skiing", "title": "Solang Valley", "description": "Discover adventure hubs for skiing, ropeway rides, and mountain fun."},
        {"icon": "fa-solid fa-road", "title": "Rohtang Pass", "description": "Drive through high-altitude roads with glacier views and snow walls."},
        {"icon": "fa-solid fa-parachute-box", "title": "Adventure Sports", "description": "Try paragliding, ATV rides, zorbing, and seasonal thrill activities."},
        {"icon": "fa-solid fa-apple-whole", "title": "Apple Orchards", "description": "Visit orchard belts and enjoy fresh mountain produce and farm scenery."},
        {"icon": "fa-solid fa-image", "title": "Scenic Valleys", "description": "Capture dramatic valleys, rivers, and pine-lined mountain settlements."},
    ],
    "kashmir-tour-package": [
        {"icon": "fa-solid fa-water", "title": "Dal Lake", "description": "Glide through iconic waters lined with houseboats and mountain views."},
        {"icon": "fa-solid fa-person-skiing", "title": "Gulmarg", "description": "Explore meadows, gondola rides, and seasonal snow experiences."},
        {"icon": "fa-solid fa-mountain-city", "title": "Pahalgam", "description": "Enjoy pine valleys, riverside views, and relaxed hillside pacing."},
        {"icon": "fa-solid fa-mountain-sun", "title": "Sonamarg", "description": "Witness glacier-fed streams and high-altitude scenic trails."},
        {"icon": "fa-solid fa-ship", "title": "Shikara Ride", "description": "Experience a classic shikara ride across serene Kashmiri waters."},
        {"icon": "fa-solid fa-tree", "title": "Mughal Gardens", "description": "Stroll through terraced gardens showcasing Persian-inspired design."},
    ],
    "golden-triangle-tour-package": [
        {"icon": "fa-solid fa-monument", "title": "Taj Mahal", "description": "Visit India's most iconic monument and timeless marble masterpiece."},
        {"icon": "fa-solid fa-fort-awesome", "title": "Amer Fort", "description": "Explore grand courtyards, palaces, and hilltop Rajput architecture."},
        {"icon": "fa-solid fa-tower-observation", "title": "Qutub Minar", "description": "Admire Delhi's UNESCO-listed minaret and historic complex."},
        {"icon": "fa-solid fa-archway", "title": "India Gate", "description": "See Delhi's ceremonial boulevard and landmark war memorial."},
        {"icon": "fa-solid fa-building-columns", "title": "City Palace", "description": "Discover royal heritage collections and ornate Jaipur courtyards."},
        {"icon": "fa-solid fa-store", "title": "Local Markets", "description": "Shop handicrafts, textiles, and street specialties across old bazaars."},
    ],
    "darjeeling-gangtok-tour-package": [
        {"icon": "fa-solid fa-mug-hot", "title": "Tea Gardens", "description": "Walk through misty tea estates with panoramic Himalayan backdrops."},
        {"icon": "fa-solid fa-sun", "title": "Tiger Hill", "description": "Catch breathtaking sunrise colors over Kanchenjunga peaks."},
        {"icon": "fa-solid fa-train", "title": "Himalayan Railway", "description": "Ride the heritage toy train through mountain towns and loops."},
        {"icon": "fa-solid fa-water", "title": "Tsomgo Lake", "description": "Visit a high-altitude glacial lake known for dramatic scenery."},
        {"icon": "fa-solid fa-road", "title": "MG Road", "description": "Enjoy Gangtok's lively promenade with cafes and shopping."},
        {"icon": "fa-solid fa-place-of-worship", "title": "Monasteries", "description": "Experience spiritual calm at iconic Buddhist monastery complexes."},
    ],
    "bhutan-tour-package": [
        {"icon": "fa-solid fa-mountain-city", "title": "Tiger's Nest Monastery", "description": "Hike to Bhutan's cliffside monastery with unforgettable valley views."},
        {"icon": "fa-solid fa-landmark", "title": "Punakha Dzong", "description": "Visit Bhutan's majestic riverside fortress with rich history."},
        {"icon": "fa-solid fa-buddha", "title": "Buddha Dordenma", "description": "See the giant seated Buddha overlooking Thimphu valley."},
        {"icon": "fa-solid fa-mountain-sun", "title": "Himalayan Views", "description": "Enjoy dramatic mountain vistas and highland valley panoramas."},
        {"icon": "fa-solid fa-people-group", "title": "Traditional Culture", "description": "Experience local festivals, architecture, and authentic Bhutanese life."},
        {"icon": "fa-solid fa-seedling", "title": "Peaceful Landscapes", "description": "Unwind in serene countryside settings and pristine natural beauty."},
    ],
    "thailand-tour-package": [
        {"icon": "fa-solid fa-ship", "title": "Island Hopping", "description": "Cruise across tropical islands with clear waters and scenic coves."},
        {"icon": "fa-solid fa-umbrella-beach", "title": "Beaches", "description": "Relax on golden beaches with lively promenades and sea views."},
        {"icon": "fa-solid fa-store", "title": "Floating Markets", "description": "Explore vibrant canal markets filled with local food and crafts."},
        {"icon": "fa-solid fa-place-of-worship", "title": "Temples", "description": "Visit ornate Buddhist temples with striking Thai architecture."},
        {"icon": "fa-solid fa-music", "title": "Nightlife", "description": "Enjoy dynamic evenings with street shows, clubs, and cafes."},
        {"icon": "fa-solid fa-person-swimming", "title": "Water Activities", "description": "Add snorkeling, speedboat rides, and beach adventures to your trip."},
    ],
    "singapore-tour-package": [
        {"icon": "fa-solid fa-hotel", "title": "Marina Bay Sands", "description": "Experience Singapore's iconic skyline zone and luxury waterfront views."},
        {"icon": "fa-solid fa-tree-city", "title": "Gardens by the Bay", "description": "Explore futuristic gardens, Supertrees, and immersive domes."},
        {"icon": "fa-solid fa-island-tropical", "title": "Sentosa Island", "description": "Enjoy beaches, attractions, and family-friendly resort experiences."},
        {"icon": "fa-solid fa-film", "title": "Universal Studios", "description": "Spend a full day on world-class rides and themed entertainment."},
        {"icon": "fa-solid fa-monument", "title": "Merlion Park", "description": "Visit Singapore's symbol with postcard skyline photo points."},
        {"icon": "fa-solid fa-paw", "title": "Night Safari", "description": "Discover after-dark wildlife encounters in curated open habitats."},
    ],
    "malaysia-tour-package": [
        {"icon": "fa-solid fa-building", "title": "Petronas Towers", "description": "See Kuala Lumpur's landmark twin towers and skyline viewpoints."},
        {"icon": "fa-solid fa-mountain", "title": "Batu Caves", "description": "Climb colorful steps to temple caves and limestone formations."},
        {"icon": "fa-solid fa-umbrella-beach", "title": "Langkawi", "description": "Enjoy island beaches, duty-free shopping, and coastal adventures."},
        {"icon": "fa-solid fa-mountain-city", "title": "Genting Highlands", "description": "Escape to cool highlands with entertainment and scenic routes."},
        {"icon": "fa-solid fa-cable-car", "title": "Cable Car", "description": "Ride panoramic cable cars over rainforest and mountain terrain."},
        {"icon": "fa-solid fa-utensils", "title": "Street Food", "description": "Taste Malaysia's diverse cuisine from bustling hawker streets."},
    ],
    "dubai-tour-package": [
        {"icon": "fa-solid fa-building", "title": "Burj Khalifa", "description": "Visit the world's tallest tower for unmatched city panoramas."},
        {"icon": "fa-solid fa-dungeon", "title": "Desert Safari", "description": "Experience dune bashing, sunset camps, and cultural performances."},
        {"icon": "fa-solid fa-water", "title": "Dubai Marina", "description": "Stroll modern waterfront promenades with skyline reflections."},
        {"icon": "fa-solid fa-tree-palm", "title": "Palm Jumeirah", "description": "Explore Dubai's iconic palm-shaped island and luxury coastlines."},
        {"icon": "fa-solid fa-bag-shopping", "title": "Dubai Mall", "description": "Shop, dine, and explore one of the largest malls in the world."},
        {"icon": "fa-solid fa-ship", "title": "Dhow Cruise", "description": "Enjoy an evening cruise with city lights and curated dining."},
    ],
    "bali-tour-package": [
        {"icon": "fa-solid fa-seedling", "title": "Rice Terraces", "description": "Walk through Bali's iconic stepped paddies and village landscapes."},
        {"icon": "fa-solid fa-place-of-worship", "title": "Uluwatu Temple", "description": "Visit dramatic cliffside temple views at sunset over the Indian Ocean."},
        {"icon": "fa-solid fa-umbrella-beach", "title": "Beaches", "description": "Relax across Bali's varied beach belts from lively to secluded."},
        {"icon": "fa-solid fa-water", "title": "Waterfalls", "description": "Discover lush jungle waterfalls and scenic natural pools."},
        {"icon": "fa-solid fa-mountain-sun", "title": "Volcano Tours", "description": "Take guided sunrise tours across Bali's volcanic highlands."},
        {"icon": "fa-solid fa-people-group", "title": "Traditional Culture", "description": "Experience Balinese dance, rituals, crafts, and temple traditions."},
    ],
}


def resolve_package_highlights(package):
    configured_highlights = DESTINATION_HIGHLIGHTS.get(package["slug"])
    if configured_highlights:
        return configured_highlights

    resolved = []
    for highlight in package.get("highlights", []):
        if isinstance(highlight, dict):
            resolved.append(highlight)
        else:
            resolved.append(
                {
                    "icon": "fa-solid fa-map-location-dot",
                    "title": str(highlight),
                    "description": "Curated stop included in this package itinerary.",
                }
            )
    return resolved

CURATED_HOLIDAY_PACKAGES = [
    {
        "slug": "kerala-tour-package",
        "title": "Kerala Tour Package",
        "theme": "Backwater Escape",
        "duration": "5 Days / 4 Nights",
        "location": "Kochi, Munnar, Thekkady, Alleppey",
        "image": "images/kerala.jpg",
        "summary": "A relaxed Kerala plan covering heritage streets, hill country, wildlife, and the calm Alleppey backwaters.",
        "highlights": [
            "Fort Kochi and Marine Drive",
            "Munnar tea gardens and viewpoints",
            "Periyar wildlife and spice plantations",
            "Alleppey houseboat cruise",
        ],
        "best_time": "September - March",
        "itinerary": [
            {"day": "Day 1", "title": "Arrival in Kochi", "plan": "Hotel check-in, Fort Kochi, Chinese Fishing Nets, and Marine Drive."},
            {"day": "Day 2", "title": "Munnar Hills", "plan": "Tea gardens, Eravikulam National Park, Echo Point, and Mattupetty Dam."},
            {"day": "Day 3", "title": "Thekkady Nature", "plan": "Periyar Wildlife Sanctuary, spice plantation visit, and Kathakali show."},
            {"day": "Day 4", "title": "Alleppey Backwaters", "plan": "Houseboat check-in, backwater cruise, local views, and sunset time."},
            {"day": "Day 5", "title": "Departure", "plan": "Breakfast and Kochi airport or railway station drop."},
        ],
    },
    {
        "slug": "goa-tour-package",
        "title": "Goa Tour Package",
        "theme": "Beach Holiday",
        "duration": "4 Days / 3 Nights",
        "location": "North Goa, South Goa",
        "image": "images/goa2.jpg",
        "summary": "A bright beach break with North Goa energy, South Goa heritage, shopping, and cruise-style evening options.",
        "highlights": [
            "North Goa beaches",
            "Fort Aguada and Baga",
            "South Goa churches",
            "Dinner cruise and shopping time",
        ],
        "best_time": "October - March",
        "itinerary": [
            {"day": "Day 1", "title": "Arrival and Beaches", "plan": "Arrival, hotel check-in, and relaxed North Goa beach time."},
            {"day": "Day 2", "title": "North Goa Circuit", "plan": "Fort Aguada, Calangute, Baga, and optional water sports."},
            {"day": "Day 3", "title": "South Goa", "plan": "Churches, scenic drives, beach stops, and cruise dinner option."},
            {"day": "Day 4", "title": "Shopping and Departure", "plan": "Local shopping, checkout, and departure transfer."},
        ],
    },
    {
        "slug": "coorg-tour-package",
        "title": "Coorg Tour Package",
        "theme": "Nature Retreat",
        "duration": "3 Days / 2 Nights",
        "location": "Madikeri, Dubare, Talacauvery",
        "image": "images/coorag.jpg",
        "summary": "A compact hill escape with waterfalls, coffee estates, elephant camp visits, and peaceful Coorg viewpoints.",
        "highlights": [
            "Raja Seat viewpoint",
            "Abbey Falls",
            "Dubare Elephant Camp",
            "Coffee plantation visit",
        ],
        "best_time": "October - May",
        "itinerary": [
            {"day": "Day 1", "title": "Madikeri Views", "plan": "Arrival, Raja Seat, Abbey Falls, and leisure time."},
            {"day": "Day 2", "title": "Dubare and Coffee", "plan": "Dubare Elephant Camp, Golden Temple, and coffee plantation experience."},
            {"day": "Day 3", "title": "Talacauvery", "plan": "Talacauvery, Bhagamandala, and departure transfer."},
        ],
    },
    {
        "slug": "chikmagalur-tour-package",
        "title": "Chikmagalur Tour Package",
        "theme": "Coffee Trails",
        "duration": "3 Days / 2 Nights",
        "location": "Mullayanagiri, Baba Budangiri, Jhari Falls",
        "image": "images/Chikkamagaluru.jpeg",
        "summary": "A scenic coffee-country getaway with peak views, waterfalls, estate routes, and soft hill-station pacing.",
        "highlights": [
            "Mullayanagiri Peak",
            "Baba Budangiri",
            "Jhari Falls",
            "Coffee estate drives",
        ],
        "best_time": "September - May",
        "itinerary": [
            {"day": "Day 1", "title": "Mullayanagiri Peak", "plan": "Arrival, check-in, Mullayanagiri Peak, and evening at leisure."},
            {"day": "Day 2", "title": "Waterfalls and Estates", "plan": "Baba Budangiri, Jhari Falls, and coffee estate route."},
            {"day": "Day 3", "title": "Lake and Departure", "plan": "Hirekolale Lake, local views, checkout, and departure."},
        ],
    },
    {
        "slug": "andaman-tour-package",
        "title": "Andaman Tour Package",
        "theme": "Island Paradise",
        "duration": "5 Days / 4 Nights",
        "location": "Port Blair, Havelock, Neil Island",
        "image": "images/andaman.jpg",
        "summary": "An island itinerary with Port Blair history, Havelock beaches, Neil Island calm, and optional water activities.",
        "highlights": [
            "Cellular Jail and Light and Sound Show",
            "Radhanagar Beach",
            "Elephant Beach water activities",
            "Neil Island visit",
        ],
        "best_time": "October - May",
        "itinerary": [
            {"day": "Day 1", "title": "Port Blair Arrival", "plan": "Arrival, Cellular Jail, and Light and Sound Show."},
            {"day": "Day 2", "title": "Havelock Island", "plan": "Transfer to Havelock Island and Radhanagar Beach visit."},
            {"day": "Day 3", "title": "Elephant Beach", "plan": "Elephant Beach and optional water sports."},
            {"day": "Day 4", "title": "Neil Island", "plan": "Neil Island transfer, beach visits, and relaxed island time."},
            {"day": "Day 5", "title": "Departure", "plan": "Checkout and departure transfer."},
        ],
    },
    {
        "slug": "bhutan-tour-package",
        "title": "Bhutan Tour Package",
        "theme": "Happiness Tour",
        "duration": "6 Days / 5 Nights",
        "location": "Paro, Thimphu, Punakha",
        "image": "images/Buthan.png",
        "summary": "A peaceful Bhutan route with monasteries, dzongs, mountain scenery, local markets, and the Tiger's Nest trek.",
        "highlights": [
            "Thimphu city experiences",
            "Punakha Dzong",
            "Suspension Bridge",
            "Tiger's Nest Monastery",
        ],
        "best_time": "March - May and September - November",
        "itinerary": [
            {"day": "Day 1", "title": "Paro to Thimphu", "plan": "Arrival at Paro and transfer to Thimphu."},
            {"day": "Day 2", "title": "Thimphu Sightseeing", "plan": "Buddha Dordenma, Memorial Chorten, and Tashichho Dzong."},
            {"day": "Day 3", "title": "Punakha", "plan": "Punakha Dzong and Suspension Bridge visit."},
            {"day": "Day 4", "title": "Tiger's Nest Trek", "plan": "Tiger's Nest Monastery trek and evening rest."},
            {"day": "Day 5", "title": "Culture and Markets", "plan": "Local market visit and cultural experience."},
            {"day": "Day 6", "title": "Departure", "plan": "Checkout and departure transfer."},
        ],
    },
    {
        "slug": "rajasthan-tour-package",
        "title": "Rajasthan Tour Package",
        "theme": "Royal Tour",
        "duration": "6 Days / 5 Nights",
        "location": "Jaipur, Jodhpur, Jaisalmer",
        "image": "images/Rajasthan-hero.jpg",
        "summary": "A royal circuit designed around forts, palaces, desert experiences, cultural evenings, and heritage city drives.",
        "highlights": [
            "Jaipur city tour",
            "Amer Fort and Jal Mahal",
            "Mehrangarh Fort",
            "Jaisalmer desert safari",
        ],
        "best_time": "October - March",
        "itinerary": [
            {"day": "Day 1", "title": "Jaipur City Tour", "plan": "Arrival and Jaipur city sightseeing."},
            {"day": "Day 2", "title": "Amer Fort", "plan": "Amer Fort, Jal Mahal, and local markets."},
            {"day": "Day 3", "title": "Jodhpur", "plan": "Transfer to Jodhpur and Mehrangarh Fort visit."},
            {"day": "Day 4", "title": "Jaisalmer", "plan": "Transfer to Jaisalmer and desert safari experience."},
            {"day": "Day 5", "title": "Desert Culture", "plan": "Camel ride and cultural night."},
            {"day": "Day 6", "title": "Departure", "plan": "Checkout and departure transfer."},
        ],
    },
    {
        "slug": "himachal-tour-package",
        "title": "Himachal Tour Package",
        "theme": "Mountain Delight",
        "duration": "6 Days / 5 Nights",
        "location": "Shimla, Kufri, Manali, Solang Valley",
        "image": "images/himachal.jpg",
        "summary": "A classic mountain holiday with Shimla charm, Kufri views, Manali leisure, Solang adventure, and seasonal snow routes.",
        "highlights": [
            "Shimla stay",
            "Kufri excursion",
            "Manali sightseeing",
            "Solang Valley and Rohtang option",
        ],
        "best_time": "March - June and October - December",
        "itinerary": [
            {"day": "Day 1", "title": "Shimla", "plan": "Arrival and Shimla local time."},
            {"day": "Day 2", "title": "Kufri", "plan": "Kufri excursion and evening at leisure."},
            {"day": "Day 3", "title": "Manali", "plan": "Transfer to Manali through scenic mountain routes."},
            {"day": "Day 4", "title": "Solang Valley", "plan": "Solang Valley sightseeing and optional activities."},
            {"day": "Day 5", "title": "Rohtang Pass", "plan": "Rohtang Pass visit when open and permitted by season."},
            {"day": "Day 6", "title": "Departure", "plan": "Checkout and departure transfer."},
        ],
    },
    {
        "slug": "hampi-tour-package",
        "title": "Hampi Tour Package",
        "theme": "Heritage Tour",
        "duration": "3 Days / 2 Nights",
        "location": "Virupaksha Temple, Vittala Temple, Anjanadri Hill",
        "image": "images/Hampi.jpeg",
        "summary": "A heritage-focused Hampi break with temple trails, stone architecture, ancient market streets, and sunrise viewpoints.",
        "highlights": [
            "Virupaksha Temple",
            "Hampi Bazaar",
            "Vittala Temple and Stone Chariot",
            "Anjanadri Hill",
        ],
        "best_time": "October - February",
        "itinerary": [
            {"day": "Day 1", "title": "Virupaksha Temple", "plan": "Arrival, Virupaksha Temple, and Hampi Bazaar walk."},
            {"day": "Day 2", "title": "Stone Chariot Trail", "plan": "Vittala Temple, Stone Chariot, and Lotus Mahal."},
            {"day": "Day 3", "title": "Anjanadri Hill", "plan": "Anjanadri Hill visit and departure transfer."},
        ],
    },
    {
        "slug": "mysore-tour-package",
        "title": "Mysore Tour Package",
        "theme": "Heritage Escape",
        "duration": "2 Days / 1 Night",
        "location": "Mysore Palace, Chamundi Hills, Brindavan Gardens",
        "image": "images/mysore-hero.jpeg",
        "summary": "A compact Mysore route built around palace interiors, market walks, viewpoints, and evening garden time.",
        "highlights": [
            "Mysore Palace visit",
            "Chamundi Hills",
            "Devaraja Market",
            "Brindavan Gardens",
        ],
        "best_time": "October - March",
        "itinerary": [
            {"day": "Day 1", "title": "Palace and City", "plan": "Arrival, Mysore Palace, St. Philomena's Church, and local market walk."},
            {"day": "Day 2", "title": "Hills and Gardens", "plan": "Chamundi Hills, zoo or museum option, Brindavan Gardens, and departure."},
        ],
    },
    {
        "slug": "ooty-tour-package",
        "title": "Ooty Tour Package",
        "theme": "Hill Retreat",
        "duration": "3 Days / 2 Nights",
        "location": "Ooty Lake, Botanical Garden, Doddabetta Peak",
        "image": "images/ooty-hero.jpeg",
        "summary": "A gentle Ooty plan with hill weather, lake views, gardens, tea routes, and relaxed sightseeing.",
        "highlights": [
            "Ooty Lake boating",
            "Botanical Garden",
            "Doddabetta Peak",
            "Tea factory stop",
        ],
        "best_time": "September - June",
        "itinerary": [
            {"day": "Day 1", "title": "Arrival and Lake", "plan": "Arrival, hotel check-in, Ooty Lake, and evening market time."},
            {"day": "Day 2", "title": "Gardens and Peaks", "plan": "Botanical Garden, Doddabetta Peak, tea factory, and scenic viewpoints."},
            {"day": "Day 3", "title": "Leisure and Departure", "plan": "Pine forest or boat house option, checkout, and departure transfer."},
        ],
    },
    {
        "slug": "dandeli-tour-package",
        "title": "Dandeli Tour Package",
        "theme": "Adventure Break",
        "duration": "3 Days / 2 Nights",
        "location": "Kali River, Syntheri Rocks, Jungle Camp",
        "image": "images/wayanad.jpg",
        "summary": "An active Dandeli getaway with river-side stays, forest drives, soft adventure, and flexible activity planning.",
        "highlights": [
            "Kali River experience",
            "Jungle stay",
            "Syntheri Rocks",
            "Adventure add-ons",
        ],
        "best_time": "October - May",
        "itinerary": [
            {"day": "Day 1", "title": "Arrival and Camp", "plan": "Arrival, camp check-in, riverside leisure, and nature walk."},
            {"day": "Day 2", "title": "Adventure Day", "plan": "Adventure activities, jungle drive, and Syntheri Rocks visit."},
            {"day": "Day 3", "title": "Scenic Departure", "plan": "Morning leisure, breakfast, checkout, and return transfer."},
        ],
    },
    {
        "slug": "darjeeling-gangtok-tour-package",
        "title": "Darjeeling & Gangtok Tour Package",
        "theme": "Eastern Hills",
        "duration": "5 Days / 4 Nights",
        "location": "Darjeeling, Tiger Hill, MG Road, Tsomgo Lake",
        "image": "images/Darjeeling-Gangtok.jpg",
        "summary": "A northeast hill journey covering tea slopes, sunrise points, monastery time, and a paced Gangtok route.",
        "highlights": [
            "Tiger Hill sunrise",
            "Darjeeling Himalayan Railway",
            "MG Road, Gangtok",
            "Tsomgo Lake",
        ],
        "best_time": "March - May and October - December",
        "itinerary": [
            {"day": "Day 1", "title": "Gangtok Arrival", "plan": "Arrival, hotel check-in, MG Road, and evening leisure."},
            {"day": "Day 2", "title": "Gangtok Excursion", "plan": "Tsomgo Lake, Baba Mandir option, and local city time."},
            {"day": "Day 3", "title": "Transfer to Darjeeling", "plan": "Scenic drive to Darjeeling and relaxed evening."},
            {"day": "Day 4", "title": "Darjeeling Highlights", "plan": "Tiger Hill sunrise, Ghoom, Batasia Loop, and tea garden views."},
            {"day": "Day 5", "title": "Departure", "plan": "Breakfast, checkout, and departure transfer."},
        ],
    },
    {
        "slug": "golden-triangle-tour-package",
        "title": "Golden Triangle Tour Package",
        "theme": "Classic India",
        "duration": "5 Days / 4 Nights",
        "location": "Delhi, Agra, Jaipur",
        "image": "images/golden triangle.jpg",
        "summary": "A classic north India circuit designed around monuments, city highlights, cultural stops, and smooth intercity travel.",
        "highlights": [
            "Delhi city tour",
            "Taj Mahal",
            "Amber Fort",
            "Jaipur markets",
        ],
        "best_time": "October - March",
        "itinerary": [
            {"day": "Day 1", "title": "Delhi Arrival", "plan": "Arrival, hotel check-in, and Delhi local sightseeing."},
            {"day": "Day 2", "title": "Delhi to Agra", "plan": "Intercity transfer, Agra Fort, and sunset view option."},
            {"day": "Day 3", "title": "Taj and Jaipur", "plan": "Taj Mahal visit and drive onward to Jaipur."},
            {"day": "Day 4", "title": "Jaipur Highlights", "plan": "Amber Fort, City Palace, Hawa Mahal, and local shopping."},
            {"day": "Day 5", "title": "Departure", "plan": "Checkout and onward transfer."},
        ],
    },
    {
        "slug": "kashmir-tour-package",
        "title": "Kashmir Tour Package",
        "theme": "Valley Escape",
        "duration": "5 Days / 4 Nights",
        "location": "Srinagar, Gulmarg, Pahalgam, Sonamarg",
        "image": "images/kashmir-5.jpg",
        "summary": "A scenic Kashmir route with valley views, mountain meadows, local gardens, and calm shikara moments.",
        "highlights": [
            "Dal Lake shikara ride",
            "Gulmarg excursion",
            "Pahalgam valley views",
            "Mughal Gardens",
        ],
        "best_time": "April - October",
        "itinerary": [
            {"day": "Day 1", "title": "Srinagar Arrival", "plan": "Arrival, hotel or houseboat check-in, and Dal Lake experience."},
            {"day": "Day 2", "title": "Gulmarg", "plan": "Full-day Gulmarg excursion and return to Srinagar."},
            {"day": "Day 3", "title": "Pahalgam", "plan": "Day trip or transfer with local valley sightseeing."},
            {"day": "Day 4", "title": "Gardens and Leisure", "plan": "Mughal Gardens, local shopping, and relaxed evening."},
            {"day": "Day 5", "title": "Departure", "plan": "Checkout and departure transfer."},
        ],
    },
    {
        "slug": "thailand-tour-package",
        "title": "Thailand Tour Package",
        "theme": "Beach and City",
        "duration": "5 Days / 4 Nights",
        "location": "Bangkok, Pattaya",
        "image": "images/thailand-4.jpg",
        "summary": "A balanced Thailand route with city highlights, island-style leisure, shopping, and relaxed transfers.",
        "highlights": [
            "Bangkok city sights",
            "Pattaya excursion",
            "Shopping and nightlife",
            "Flexible family pacing",
        ],
        "best_time": "November - March",
        "itinerary": [
            {"day": "Day 1", "title": "Arrival", "plan": "Arrival, hotel check-in, and evening leisure."},
            {"day": "Day 2", "title": "Bangkok", "plan": "City highlights, temple area, and shopping time."},
            {"day": "Day 3", "title": "Pattaya", "plan": "Transfer to Pattaya and beachside leisure."},
            {"day": "Day 4", "title": "Excursion Day", "plan": "Coral Island or local excursion options with return."},
            {"day": "Day 5", "title": "Departure", "plan": "Checkout and departure transfer."},
        ],
    },
    {
        "slug": "singapore-tour-package",
        "title": "Singapore Tour Package",
        "theme": "City Escape",
        "duration": "4 Days / 3 Nights",
        "location": "Marina Bay, Sentosa, Gardens by the Bay",
        "image": "images/singapore-8.jpg",
        "summary": "A compact Singapore holiday focused on major attractions, clean transfers, and flexible city time.",
        "highlights": [
            "Marina Bay skyline",
            "Sentosa attractions",
            "Gardens by the Bay",
            "Shopping districts",
        ],
        "best_time": "February - April",
        "itinerary": [
            {"day": "Day 1", "title": "Arrival", "plan": "Arrival, hotel check-in, and evening waterfront time."},
            {"day": "Day 2", "title": "City Highlights", "plan": "Merlion, Marina Bay, Gardens by the Bay, and leisure."},
            {"day": "Day 3", "title": "Sentosa", "plan": "Sentosa attractions and city return."},
            {"day": "Day 4", "title": "Departure", "plan": "Checkout and airport transfer."},
        ],
    },
    {
        "slug": "malaysia-tour-package",
        "title": "Malaysia Tour Package",
        "theme": "City and Highlands",
        "duration": "5 Days / 4 Nights",
        "location": "Kuala Lumpur, Genting Highlands, Putrajaya",
        "image": "images/Malaysia-hero.jpg",
        "summary": "A Malaysia plan combining city icons, highland leisure, shopping time, and smooth urban sightseeing.",
        "highlights": [
            "Petronas Towers area",
            "Genting Highlands",
            "Putrajaya landmarks",
            "Shopping and food trails",
        ],
        "best_time": "December - April",
        "itinerary": [
            {"day": "Day 1", "title": "Kuala Lumpur Arrival", "plan": "Arrival, check-in, and city orientation."},
            {"day": "Day 2", "title": "City Highlights", "plan": "KL city tour, towers area, and local shopping."},
            {"day": "Day 3", "title": "Genting Excursion", "plan": "Full-day Genting Highlands trip and cable car option."},
            {"day": "Day 4", "title": "Putrajaya", "plan": "Putrajaya landmarks and flexible leisure evening."},
            {"day": "Day 5", "title": "Departure", "plan": "Checkout and airport transfer."},
        ],
    },
    {
        "slug": "dubai-tour-package",
        "title": "Dubai Tour Package",
        "theme": "City Luxury",
        "duration": "5 Days / 4 Nights",
        "location": "Dubai City, Marina, Desert Safari, Abu Dhabi option",
        "image": "images/Dubai-hero.jpg",
        "summary": "A Dubai itinerary balancing skyline stops, shopping, marina evenings, desert safari, and optional day tours.",
        "highlights": [
            "Dubai city tour",
            "Desert safari",
            "Burj Khalifa area",
            "Marina and shopping",
        ],
        "best_time": "November - March",
        "itinerary": [
            {"day": "Day 1", "title": "Arrival and Marina", "plan": "Arrival, hotel check-in, and marina leisure."},
            {"day": "Day 2", "title": "City Highlights", "plan": "Dubai city sightseeing and Burj Khalifa district visit."},
            {"day": "Day 3", "title": "Desert Safari", "plan": "Leisure first half and evening desert safari."},
            {"day": "Day 4", "title": "Flexible Touring", "plan": "Shopping, optional Abu Dhabi, or resort leisure."},
            {"day": "Day 5", "title": "Departure", "plan": "Checkout and airport transfer."},
        ],
    },
    {
        "slug": "bali-tour-package",
        "title": "Bali Tour Package",
        "theme": "Island Escape",
        "duration": "5 Days / 4 Nights",
        "location": "Ubud, Kintamani, Seminyak, Uluwatu",
        "image": "images/bali-10.jpg",
        "summary": "A Bali holiday covering temples, rice terraces, coastline leisure, and flexible private touring.",
        "highlights": [
            "Ubud and rice terraces",
            "Kintamani views",
            "Uluwatu sunset",
            "Beachside leisure",
        ],
        "best_time": "April - October",
        "itinerary": [
            {"day": "Day 1", "title": "Arrival", "plan": "Arrival, hotel check-in, and relaxed evening."},
            {"day": "Day 2", "title": "Ubud", "plan": "Ubud route, cultural stops, and scenic countryside."},
            {"day": "Day 3", "title": "Kintamani", "plan": "Highland sightseeing and local touring."},
            {"day": "Day 4", "title": "Coast and Sunset", "plan": "Beach leisure and Uluwatu sunset route."},
            {"day": "Day 5", "title": "Departure", "plan": "Checkout and airport transfer."},
        ],
    },
]


def curated_package_items():
    return [
        {
            **package,
            "highlights": resolve_package_highlights(package),
            "image_url": safe_static_image(package["image"]),
        }
        for package in CURATED_HOLIDAY_PACKAGES
    ]


INTERNATIONAL_PACKAGE_SLUGS = {
    "bhutan-tour-package",
    "thailand-tour-package",
    "singapore-tour-package",
    "malaysia-tour-package",
    "dubai-tour-package",
    "bali-tour-package",
}


KARNATAKA_TEMPLE_TOUR_ITINERARIES = [
    {
        "slug": "karnataka-temple-travel",
        "title": "Karnataka Temple Travel",
        "theme": "Temple Circuit",
        "duration": "4 Days / 3 Nights",
        "location": "Kukke, Murudeshwar, Kollur, Udupi",
        "image": "images/Kukke Subramanya.jpeg",
        "summary": "A balanced temple circuit covering sacred inland and coastal Karnataka routes with comfortable transfers.",
        "highlights": [
            "Kukke Subramanya darshan",
            "Murudeshwar coastal temple visit",
            "Kollur Mookambika temple",
            "Udupi Krishna temple",
        ],
        "best_time": "September - March",
        "itinerary": [
            {"day": "Day 1", "title": "Arrive and Begin Pilgrimage", "plan": "Arrive in Kukke, complete darshan, and settle in for the night."},
            {"day": "Day 2", "title": "Coastal Temple Route", "plan": "Proceed to Murudeshwar and visit temple and coastline viewpoints."},
            {"day": "Day 3", "title": "Kollur and Udupi", "plan": "Visit Kollur Mookambika and continue to Udupi Krishna temple."},
            {"day": "Day 4", "title": "Departure", "plan": "Morning temple visit and return transfer to your selected drop point."},
        ],
    },
    {
        "slug": "coastal-karnataka",
        "title": "Coastal Karnataka",
        "theme": "Coastal Pilgrimage",
        "duration": "3 Days / 2 Nights",
        "location": "Murudeshwar, Udupi, Gokarna",
        "image": "images/Murudeshwar.jpeg",
        "summary": "A serene coastal route combining sea-facing temples, devotional stops, and scenic Arabian Sea drives.",
        "highlights": [
            "Murudeshwar temple and beach",
            "Udupi Krishna temple",
            "Gokarna coastal temple visit",
            "Sunrise and sunset coastal stretches",
        ],
        "best_time": "October - March",
        "itinerary": [
            {"day": "Day 1", "title": "Murudeshwar Arrival", "plan": "Arrive and visit Murudeshwar temple complex and coastal zone."},
            {"day": "Day 2", "title": "Udupi Temple Route", "plan": "Travel to Udupi, attend temple darshan, and explore nearby spiritual sites."},
            {"day": "Day 3", "title": "Gokarna and Return", "plan": "Visit Gokarna temple route and proceed for departure."},
        ],
    },
    {
        "slug": "sringeri-kollur-udupi-dharmasthala-kukke",
        "title": "Sringeri -> Kollur -> Udupi -> Dharmasthala -> Kukke",
        "theme": "Classic Temple Belt",
        "duration": "5 Days / 4 Nights",
        "location": "Sringeri, Kollur, Udupi, Dharmasthala, Kukke",
        "image": "images/Horanadu.jpeg",
        "summary": "A complete western temple belt itinerary through Karnataka's most revered and connected pilgrimage towns.",
        "highlights": [
            "Sringeri Sharada Peetham",
            "Kollur Mookambika temple",
            "Udupi Krishna temple",
            "Dharmasthala and Kukke darshan",
        ],
        "best_time": "September - February",
        "itinerary": [
            {"day": "Day 1", "title": "Sringeri", "plan": "Arrive at Sringeri and complete temple rituals."},
            {"day": "Day 2", "title": "Sringeri to Kollur", "plan": "Travel to Kollur and attend Mookambika temple darshan."},
            {"day": "Day 3", "title": "Kollur to Udupi", "plan": "Proceed to Udupi and visit Krishna temple with evening rest."},
            {"day": "Day 4", "title": "Udupi to Dharmasthala", "plan": "Visit Dharmasthala temple and continue according to schedule."},
            {"day": "Day 5", "title": "Kukke and Departure", "plan": "Complete Kukke darshan and return transfer."},
        ],
    },
    {
        "slug": "sringeri-hornadu-udupi-dharmasthala-kukke",
        "title": "Sringeri -> Hornadu -> Udupi -> Dharmasthala -> Kukke",
        "theme": "Hill to Coastal Temple Route",
        "duration": "5 Days / 4 Nights",
        "location": "Sringeri, Hornadu, Udupi, Dharmasthala, Kukke",
        "image": "images/Horanadu.jpeg",
        "summary": "A spiritual itinerary combining Sringeri and Hornadu hill temples with major coastal and inland shrines.",
        "highlights": [
            "Sringeri Sharada temple",
            "Hornadu Annapoorneshwari temple",
            "Udupi Krishna temple",
            "Dharmasthala and Kukke circuit",
        ],
        "best_time": "September - February",
        "itinerary": [
            {"day": "Day 1", "title": "Sringeri Arrival", "plan": "Arrive at Sringeri and complete main temple visit."},
            {"day": "Day 2", "title": "Hornadu Darshan", "plan": "Travel to Hornadu and visit Annapoorneshwari temple."},
            {"day": "Day 3", "title": "Hornadu to Udupi", "plan": "Proceed to Udupi for temple darshan and rest."},
            {"day": "Day 4", "title": "Dharmasthala", "plan": "Visit Dharmasthala temple and continue to next stay."},
            {"day": "Day 5", "title": "Kukke and Return", "plan": "Complete Kukke darshan and depart."},
        ],
    },
    {
        "slug": "gokarna-murudeshwar-udupi-hornadu-dharmasthala-kukke",
        "title": "Gokarna -> Murudeshwar -> Udupi -> Hornadu -> Dharmasthala -> Kukke",
        "theme": "Extended Temple Circuit",
        "duration": "6 Days / 5 Nights",
        "location": "Gokarna, Murudeshwar, Udupi, Hornadu, Dharmasthala, Kukke",
        "image": "images/Murudeshwar.jpeg",
        "summary": "An extended temple route that links the coast, ghats, and key Karnataka spiritual centers in one journey.",
        "highlights": [
            "Gokarna temple route",
            "Murudeshwar coastal shrine",
            "Udupi and Hornadu darshan",
            "Dharmasthala and Kukke completion",
        ],
        "best_time": "October - March",
        "itinerary": [
            {"day": "Day 1", "title": "Gokarna", "plan": "Arrive in Gokarna and begin temple visits."},
            {"day": "Day 2", "title": "Murudeshwar", "plan": "Travel to Murudeshwar and visit temple complex."},
            {"day": "Day 3", "title": "Udupi", "plan": "Proceed to Udupi for darshan and local temple circuit."},
            {"day": "Day 4", "title": "Hornadu", "plan": "Visit Hornadu temple with ghat-route travel."},
            {"day": "Day 5", "title": "Dharmasthala", "plan": "Attend Dharmasthala temple and continue onward."},
            {"day": "Day 6", "title": "Kukke and Departure", "plan": "Complete Kukke temple visit and return transfer."},
        ],
    },
    {
        "slug": "kollur-murudeshwar-gokarna",
        "title": "Kollur -> Murudeshwar -> Gokarna",
        "theme": "Short Coastal Temple Escape",
        "duration": "3 Days / 2 Nights",
        "location": "Kollur, Murudeshwar, Gokarna",
        "image": "images/Kukke Subramanya.jpeg",
        "summary": "A short spiritual coastal getaway focused on three major temple destinations with easy pacing.",
        "highlights": [
            "Kollur Mookambika temple",
            "Murudeshwar Shiva complex",
            "Gokarna pilgrimage stop",
            "Comfortable coastal travel",
        ],
        "best_time": "October - March",
        "itinerary": [
            {"day": "Day 1", "title": "Kollur", "plan": "Arrive and complete darshan at Kollur Mookambika temple."},
            {"day": "Day 2", "title": "Murudeshwar", "plan": "Proceed to Murudeshwar for temple and coastal sightseeing."},
            {"day": "Day 3", "title": "Gokarna and Return", "plan": "Visit Gokarna temples and depart for your drop location."},
        ],
    },
]


def karnataka_temple_tour_items():
    return [
        {
            **package,
            "highlights": resolve_package_highlights(package),
            "image_url": safe_static_image(package["image"]),
        }
        for package in KARNATAKA_TEMPLE_TOUR_ITINERARIES
    ]


def karnataka_temple_tour_for_slug(package_slug):
    for package in karnataka_temple_tour_items():
        if package["slug"] == package_slug:
            return package

    raise Http404("Karnataka temple itinerary not found.")


KARNATAKA_PACKAGE_PAGES = {
    "karnataka-tour-packages": {
        "slug": "karnataka-tour-packages",
        "title": "Karnataka Tour Packages",
        "theme": "Complete Karnataka Travel",
        "duration": "Flexible - 3 to 10 Days",
        "location": "Mysore, Hampi, Coorg, Chikkamagaluru",
        "image": "images/mysore-hero.jpeg",
        "summary": "Structured Karnataka holiday plans that combine heritage, hill stations, temples, beaches, and private cab touring in one premium package.",
        "best_time": "September - March",
        "overview": "Explore Karnataka with tailored itineraries across historical cities, lush hills, serene temples, and coastal destinations. These package pages present curated experiences, practical travel details, and private cab support.",
        "why_choose": [
            "A carefully balanced Karnataka itinerary for culture, nature, and comfort.",
            "Private cab travel with clear pickup, drop, and sightseeing coordination.",
            "Flexible routes that can be shortened, extended, or upgraded to suit your group.",
        ],
        "destinations": [
            {"title": "Mysore Palace & Heritage", "description": "Royal Mysore and its cultural landmarks offer regal architecture, markets, and curated city touring."},
            {"title": "Hampi Ancient Ruins", "description": "World heritage temples, majestic stone chariots, and dramatic boulder landscapes set a historic tone."},
            {"title": "Coorg & Chikkamagaluru Hills", "description": "Coffee plantations, waterfalls, and hill views create the perfect nature and leisure itinerary."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-map-location-dot", "title": "Multi-region Karnataka", "description": "Every itinerary highlights the best sections of Karnataka in one connected trip."},
            {"icon": "fa-solid fa-car", "title": "Private Cab Support", "description": "Safe chauffeur-driven travel for all Karnataka pickup and return transfers."},
            {"icon": "fa-solid fa-landmark", "title": "Heritage and Temple Niches", "description": "From Mysore palace halls to Hampi temple ruins, each route has premium heritage stops."},
            {"icon": "fa-solid fa-mountain", "title": "Hill Station Comfort", "description": "Coorg, Chikkamagaluru, and Ooty-style hill station experiences balance every journey."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Arrival and Karnataka Welcome", "plan": "Begin with pickup and a relaxed welcome drive. Explore city highlights with a private guide and settle into your first hotel."},
            {"day": "Day 2", "title": "Heritage Discoveries", "plan": "Visit royal heritage sites, historic temples, and curated city viewpoints before moving deeper into Karnataka."},
            {"day": "Day 3", "title": "Hills and Coffee", "plan": "Travel into Coorg or Chikkamagaluru, enjoy coffee plantation tours, waterfall visits, and comfortable hill-side lodging."},
            {"day": "Day 4", "title": "Beach and Temple Routes", "plan": "Combine coastal or temple destinations with local sightseeing, relaxed drive time, and evening leisure."},
            {"day": "Day 5", "title": "Customize Your Return", "plan": "Finish with an easy departure transfer, optional shopping stop, and a seamless ride back to your start point."},
        ],
        "cab_info": [
            "Private air-conditioned cab for all Karnataka travel legs.",
            "Trusted local driver with Karnataka route knowledge.",
            "Flexible pickup from Bangalore, Mysore, or airport locations.",
        ],
        "faq": [
            {"question": "Can I change the Karnataka route?", "answer": "Yes. Each package can be customized with alternative stops, extra days, and different accommodation standards."},
            {"question": "Is the cab included for sightseeing?", "answer": "A private cab is included in the package for planned routes, sightseeing transfers, and day trips according to your itinerary."},
            {"question": "What is the best season to visit Karnataka?", "answer": "September through March is the most comfortable season for heritage visits, hill stations, coastal trips, and outdoor touring."},
        ],
        "related_slugs": ["karnataka-honeymoon-packages", "karnataka-heritage-packages", "karnataka-beach-packages"],
    },
    "karnataka-honeymoon-packages": {
        "slug": "karnataka-honeymoon-packages",
        "title": "Karnataka Honeymoon Packages",
        "theme": "Romantic Escapes",
        "duration": "4 Days / 3 Nights",
        "location": "Coorg, Chikkamagaluru, Mysore",
        "image": "images/coorag.jpg",
        "summary": "Romantic Karnataka packages designed for honeymooners, featuring cozy hill stays, scenic drives, and intimate nature experiences.",
        "best_time": "October - February",
        "overview": "Choose an intimate Karnataka honeymoon with peaceful mornings, romantic viewpoints, and private travel arrangements across the hill stations and heritage cities.",
        "why_choose": [
            "Private property stays with romantic dining options.",
            "Smooth itinerary pacing for couples who want both adventure and relaxation.",
            "Custom honeymoon touches like sunset viewpoints and coffee estate walks.",
        ],
        "destinations": [
            {"title": "Coorg Romance", "description": "Spend time in serene Coorg resorts, enjoy waterfalls, and stroll aromatic coffee estates with your partner."},
            {"title": "Chikkamagaluru Vistas", "description": "Explore misty hills, scenic tea and coffee trails, and quiet lakeside viewpoints ideal for couples."},
            {"title": "Mysore Heritage", "description": "Add royal elegance to the honeymoon with palace visits, cultural performances, and elegant evening experiences."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-heart", "title": "Romantic Hill Stays", "description": "Comfortable stays in premium hill properties with views and privacy."},
            {"icon": "fa-solid fa-mug-hot", "title": "Coffee Estate Walks", "description": "Private plantation tours with coffee tasting and fragrant estate routes."},
            {"icon": "fa-solid fa-camera", "title": "Sunset Moments", "description": "Curated sunset points, scenic drives, and candlelit dining opportunities."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Arrival in Coorg", "plan": "Arrive in the hill station, settle into your resort, and enjoy a romantic evening with local cuisine."},
            {"day": "Day 2", "title": "Coffee Trails and Waterfalls", "plan": "Visit a coffee plantation, experience a guided estate walk, then enjoy a late afternoon waterfall drive."},
            {"day": "Day 3", "title": "Chikkamagaluru Hills", "plan": "Drive toward Chikkamagaluru, explore mountain viewpoints, and unwind at a scenic hilltop property."},
            {"day": "Day 4", "title": "Mysore Elegance", "plan": "Visit Mysore Palace, shop for local heirloom crafts, and return with a private transfer to your departure point."},
        ],
        "cab_info": [
            "Private honeymoon cab with comfortable seating and luggage space.",
            "Flexible route stops for photography, dining, and quiet viewpoints.",
        ],
        "faq": [
            {"question": "Will the driver respect our privacy?", "answer": "Yes. Drivers are briefed to provide discreet service and smooth travel without disturbing your private moments."},
            {"question": "Can I add a luxury cottage stay?", "answer": "Yes. We can recommend premium properties and upgrade options based on your honeymoon package."},
        ],
        "related_slugs": ["karnataka-hill-station-packages", "coffee-plantation-tours", "family-holiday-packages"],
    },
    "karnataka-hill-station-packages": {
        "slug": "karnataka-hill-station-packages",
        "title": "Karnataka Hill Station Packages",
        "theme": "Misty Highlands",
        "duration": "3 Days / 2 Nights",
        "location": "Ooty, Coorg, Chikkamagaluru",
        "image": "images/ooty-hero.jpeg",
        "summary": "Hill station packages for cool weather escapes, tea garden views, and scenic mountain drive experiences.",
        "best_time": "October - June",
        "overview": "Enjoy Karnataka's hill station charm with elevated resorts, lush valleys, and scenic mountain routes designed for calm and comfort.",
        "why_choose": [
            "Cool weather hill escapes with premium travel support.",
            "Easy access to plantation walks and hilltop viewpoints.",
            "Relaxed itineraries suited for couples, families, and small groups.",
        ],
        "destinations": [
            {"title": "Ooty’s Lakes and Gardens", "description": "Fresh mountain air, garden landscapes, and serene boat rides in one of South India's most popular hill stations."},
            {"title": "Coorg's Coffee Hills", "description": "Gentle waterfalls, coffee trails, and panoramic ridge views make Coorg a hill-station travel favorite."},
            {"title": "Chikkamagaluru Peaks", "description": "Mullayanagiri and Baba Budangiri offer accessible trekking, viewpoint stops, and misty mornings."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-tree-pine", "title": "Tea and Coffee Estates", "description": "Enjoy the cool hill fragrance of estates and high-altitude plantation walks."},
            {"icon": "fa-solid fa-umbrella-beach", "title": "Lakes and Gardens", "description": "Relax beside lakes, gardens, and scenic viewpoints away from the city heat."},
            {"icon": "fa-solid fa-road", "title": "Scenic Drives", "description": "Drive through mist-lined ghat roads and enjoy comfortable hill travel."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Arrival and Lake Walk", "plan": "Arrive at the hill station and spend the afternoon at a lake or garden with a gentle walking route."},
            {"day": "Day 2", "title": "Estate and Viewpoint Tour", "plan": "Visit tea or coffee estates, explore local viewpoints, and enjoy an evening with hill station vistas."},
            {"day": "Day 3", "title": "Leisure and Departure", "plan": "Spend a relaxed morning, visit a market for local produce, and depart with a comfortable return transfer."},
        ],
        "cab_info": [
            "Hill-capable cab with experienced driver for ghat road driving.",
            "Flexible pickup and drop from nearby city or airport locations.",
        ],
        "faq": [
            {"question": "Are road conditions safe for hill travel?", "answer": "Yes. The route is planned with experienced drivers and appropriate vehicles for hill roads."},
            {"question": "Can I shorten or extend the hill stay?", "answer": "Yes. We can modify the package duration based on your preferred pace and available dates."},
        ],
        "related_slugs": ["weekend-getaway-packages", "coffee-plantation-tours", "nature-eco-tourism-packages"],
    },
    "karnataka-heritage-packages": {
        "slug": "karnataka-heritage-packages",
        "title": "Karnataka Heritage Packages",
        "theme": "Historic Journeys",
        "duration": "4 Days / 3 Nights",
        "location": "Hampi, Mysore, Badami",
        "image": "images/Hampi.jpeg",
        "summary": "Heritage-focused Karnataka tours that bring royal palaces, temple ruins, and UNESCO-listed landscapes into one cultural itinerary.",
        "best_time": "October - February",
        "overview": "Visit Karnataka’s ancient and royal landmarks with expert routing, comfortable transport, and curated heritage highlights.",
        "why_choose": [
            "Guided heritage routes through UNESCO and royal sites.",
            "Private cab transfers between historic Karnataka destinations.",
            "Balanced touring with cultural sightseeing and relaxed afternoons.",
        ],
        "destinations": [
            {"title": "Hampi Ruins", "description": "Walk through the iconic ancient temples, stone chariot, and riverfront vistas of the Vijayanagara empire."},
            {"title": "Mysore Royalty", "description": "Explore palaces, landmark temples, and the city’s cultural showcase with expert direction."},
            {"title": "Badami Caves", "description": "Discover ancient cave temples carved into red sandstone cliffs along Karnataka’s heritage circuit."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-landmark", "title": "UNESCO Heritage", "description": "Heritage sites including Hampi and royal Mysore architecture."},
            {"icon": "fa-solid fa-place-of-worship", "title": "Temple Splendor", "description": "Historic temples with exquisite carving and monumental design."},
            {"icon": "fa-solid fa-camera", "title": "Iconic Photography", "description": "Capture dramatic ruins, royal halls, and timeless Karnataka vistas."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Arrival and Palace Tour", "plan": "Arrive in Mysore, visit the palace and Chamundi Hills, and settle into a comfortable city hotel."},
            {"day": "Day 2", "title": "Hampi Heritage", "plan": "Transfer to Hampi, visit the Virupaksha and Vittala complexes, and explore old market areas."},
            {"day": "Day 3", "title": "Ancient Caves", "plan": "Visit the historical rock-cut cave temples of Badami and nearby heritage monuments."},
            {"day": "Day 4", "title": "Return Journey", "plan": "Enjoy a leisure breakfast, a last heritage stop, and a transfer back to your departure city."},
        ],
        "cab_info": [
            "Heritage circuit cab transfers tailored for comfortable sightseeing.",
            "Driver guidance for historic stop planning and route timing.",
        ],
        "faq": [
            {"question": "Can this package include a local guide?", "answer": "Yes. Guided heritage tours can be arranged for Hampi, Mysore, and Badami visits."},
            {"question": "Is entry ticketing included?", "answer": "Entry tickets can be arranged as part of the package or quoted separately based on the chosen attractions."},
        ],
        "related_slugs": ["karnataka-tour-packages", "pilgrimage-tour-packages", "family-holiday-packages"],
    },
    "karnataka-wildlife-packages": {
        "slug": "karnataka-wildlife-packages",
        "title": "Karnataka Wildlife Packages",
        "theme": "Nature Safaris",
        "duration": "3 Days / 2 Nights",
        "location": "Karnataka Western Ghats and Reserve Routes",
        "image": "images/Hirekolale Lake.jpg",
        "summary": "Wildlife and forest-friendly Karnataka escapes focused on nature trails, birdwatching, and protected habitat experiences.",
        "best_time": "September - February",
        "overview": "Experience Karnataka’s biodiversity with forest trail walks, lake-side nature viewing, and carefully selected wildlife-friendly day plans.",
        "why_choose": [
            "Nature-led routes around Karnataka’s western hill corridor.",
            "Birdwatching, scenic lake walks, and forest reserve access.",
            "Private cab transfers to natural viewpoints and peaceful environments.",
        ],
        "destinations": [
            {"title": "Hirekolale Lake", "description": "A calm lake setting in Chikkamagaluru perfect for early morning birdwatching and reflective nature walks."},
            {"title": "Western Ghats Greenery", "description": "Forest-clad routes and misty hills offer a serene environmental experience."},
            {"title": "Wildlife-Friendly Stops", "description": "Enjoy guided nature drives and forest-edge experiences without disturbing local habitats."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-binoculars", "title": "Birdwatching", "description": "Spot local birdlife, forest-edge species, and lakeside wildlife activity."},
            {"icon": "fa-solid fa-tree", "title": "Nature Trails", "description": "Gentle walks through forest groves, coffee trails, and quiet hill routes."},
            {"icon": "fa-solid fa-water", "title": "Lakeside Views", "description": "Enjoy serene lake stops with misty morning scenery and reflective water views."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Arrival and Nature Walk", "plan": "Arrive at your wildlife gateway, enjoy a lakeside walk, and settle into a comfortable forest-side stay."},
            {"day": "Day 2", "title": "Birdwatching and Scenic Routes", "plan": "Spend the day exploring natural trails, lake viewpoints, and gentle forest drives."},
            {"day": "Day 3", "title": "Return with Green Stops", "plan": "Enjoy a relaxed morning, visit a scenic viewpoint, and travel back to your departure location."},
        ],
        "cab_info": [
            "Private cab for wildlife-friendly routes and reserve-edge transfers.",
            "Flexible journey planning around nature stops and daylight hours.",
        ],
        "faq": [
            {"question": "Are wildlife sightings guaranteed?", "answer": "Wildlife sightings cannot be guaranteed, but the itinerary is designed around high-probability forest and lake habitats."},
            {"question": "What clothing should I pack?", "answer": "Pack comfortable travel clothes, light layers, and closed shoes for nature walks."},
        ],
        "related_slugs": ["nature-eco-tourism-packages", "weekend-getaway-packages", "coffee-plantation-tours"],
    },
    "karnataka-beach-packages": {
        "slug": "karnataka-beach-packages",
        "title": "Karnataka Beach Packages",
        "theme": "Coastal Escapes",
        "duration": "3 Days / 2 Nights",
        "location": "Murudeshwar, Udupi",
        "image": "images/Murudeshwar.jpeg",
        "summary": "Coastal Karnataka beach packages with sunrise shorelines, seaside temples, and relaxed ocean-view stays.",
        "best_time": "November - March",
        "overview": "Enjoy Karnataka’s coastal charm with beach walks, temple views, and private cab travel between Murudeshwar and Udupi.",
        "why_choose": [
            "Picturesque beachfront villages and calm coastal drives.",
            "Temples and shorelines combined for a meaningful coastal escape.",
            "Private cab transit that keeps the route smooth and scenic.",
        ],
        "destinations": [
            {"title": "Murudeshwar Temple Beach", "description": "The iconic Murudeshwar temple and beach area are ideal for both shoreline relaxation and spiritual visiting."},
            {"title": "Udupi Coast", "description": "Enjoy coastal temples, local cuisine, and gentle beachside strolling in Udupi."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-umbrella-beach", "title": "Coastal Sunrises", "description": "Watch the first light over the Arabian Sea from Karnataka’s quiet beach destinations."},
            {"icon": "fa-solid fa-place-of-worship", "title": "Temple-Sea Harmony", "description": "Visit shore-facing temples and enjoy coastal spirituality."},
            {"icon": "fa-solid fa-fish-fins", "title": "Beach Leisure", "description": "Relax with seaside walks, seafood dining, and calm coastal pacing."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Murudeshwar Arrival", "plan": "Arrive in Murudeshwar, visit the temple, enjoy the beach, and settle into your seaside stay."},
            {"day": "Day 2", "title": "Udupi Coastline", "plan": "Travel down the coast to Udupi, explore local temples, and relax by the beach."},
            {"day": "Day 3", "title": "Relax and Depart", "plan": "Enjoy a calm morning, coastal coffee stop, and transfer to your next destination."},
        ],
        "cab_info": [
            "Coastal cab transfer with comfortable short-distance travel.",
            "Assistance to reach beach viewpoints and temple entry points.",
        ],
        "faq": [
            {"question": "Can this package include water sports?", "answer": "Water sports can be arranged separately where available, depending on the beach destination."},
            {"question": "Is there a good time for beach weather?", "answer": "November through March offers the most pleasant beach weather in Karnataka."},
        ],
        "related_slugs": ["karnataka-temple-packages", "pilgrimage-tour-packages", "family-holiday-packages"],
    },
    "karnataka-temple-packages": {
        "slug": "karnataka-temple-packages",
        "title": "Karnataka Temple Packages",
        "theme": "Sacred Journeys",
        "duration": "4 Days / 3 Nights",
        "location": "Kukke, Murudeshwar, Horanadu",
        "image": "images/Kukke Subramanya.jpeg",
        "summary": "Sacred temple tours across Karnataka combining famous pilgrimage destinations with thoughtful travel planning.",
        "best_time": "September - February",
        "overview": "Visit Karnataka’s most revered temples with private cab travel, calm itineraries, and pilgrimage-friendly route planning.",
        "why_choose": [
            "Pilgrimage-ready planning for temple visits and darshan times.",
            "Private cab routes that minimize transfer stress between spiritual destinations.",
            "Calm stay options close to temples and convenient travel support.",
        ],
        "destinations": [
            {"title": "Kukke Subramanya", "description": "A revered hill temple destination known for its snake worship, serene surroundings, and important rituals."},
            {"title": "Murudeshwar Temple", "description": "A coastal temple complex with a monumental Shiva statue and calming beach vistas."},
            {"title": "Horanadu and Kateel", "description": "Sacred river temples set in peaceful hill and riverside settings."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-place-of-worship", "title": "Holy Temple Circuit", "description": "Visit some of Karnataka’s most respected temple destinations in one journey."},
            {"icon": "fa-solid fa-hands-praying", "title": "Pilgrimage Comfort", "description": "Smooth transfers, restful stays, and itinerary pacing designed for spiritual travel."},
            {"icon": "fa-solid fa-road", "title": "Managed Transit", "description": "Private cab support keeps your pilgrimage route efficient and peaceful."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Kukke Subramanya", "plan": "Reach Kukke, perform darshan, and stay near the temple complex with a calm evening."},
            {"day": "Day 2", "title": "Murudeshwar Temple", "plan": "Travel to Murudeshwar, visit the temple and beach, and rest at a coastal stay."},
            {"day": "Day 3", "title": "Horanadu and Kateel", "plan": "Visit hill and riverside temples, enjoy a peaceful temple experience, and prepare for return."},
            {"day": "Day 4", "title": "Departure", "plan": "After breakfast, begin your return journey to Bangalore or your next destination."},
        ],
        "cab_info": [
            "Pilgrimage cab service with comfortable travel between temples.",
            "Assistance for darshan planning and local temple information.",
        ],
        "faq": [
            {"question": "Can the package include temple bookings?", "answer": "Yes, darshan support and temple booking guidance can be provided where available."},
            {"question": "Is there an option for vegetarian meals?", "answer": "Yes. Vegetarian meals can be arranged at recommended stays and dining locations."},
        ],
        "related_slugs": ["karnataka-tour-packages", "karnataka-beach-packages", "pilgrimage-tour-packages"],
    },
    "pilgrimage-tour-packages": {
        "slug": "pilgrimage-tour-packages",
        "title": "Pilgrimage Tour Packages",
        "theme": "Sacred Karnataka",
        "duration": "4 Days / 3 Nights",
        "location": "Kukke, Murudeshwar, Horanadu",
        "image": "images/Kukke Subramanya.jpeg",
        "summary": "Pilgrimage packages that connect Karnataka’s most revered temples with comfortable private cab travel and calm itinerary pacing.",
        "best_time": "September - February",
        "overview": "Experience Karnataka’s spiritual highlights with private cab support, restful temple stays, and a planned route that honors darshan times and serenity.",
        "why_choose": [
            "Private cab travel for pilgrimage convenience and easy temple access.",
            "Carefully paced routes that include major Karnataka temples and coastal spirituality.",
            "Calm stay options near temples with support for vegetarian meals and local rituals.",
        ],
        "destinations": [
            {"title": "Kukke Subramanya", "description": "A revered hill temple destination known for its snake worship rituals and peaceful setting."},
            {"title": "Murudeshwar Temple", "description": "A coastal temple complex with a giant Shiva statue and soothing Arabian Sea views."},
            {"title": "Horanadu Temple", "description": "A serene riverside temple known for its devotional atmosphere and traditional Karnataka cuisine."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-place-of-worship", "title": "Temple Darshan Planning", "description": "Organized visits with private cab transfers timed for darshan and ease."},
            {"icon": "fa-solid fa-hand-holding-heart", "title": "Spiritual Route", "description": "A soulful Karnataka route connecting coastal and hilltop temples."},
            {"icon": "fa-solid fa-road", "title": "Comfortable Transfers", "description": "Private cab support ensures smooth, calm travel between pilgrimage sites."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Kukke Subramanya Arrival", "plan": "Arrive in Kukke, complete darshan at Subramanya Temple, and relax at your temple-area stay."},
            {"day": "Day 2", "title": "Murudeshwar Temple Visit", "plan": "Travel to Murudeshwar, visit the temple complex and beach shoreline, and rest in a coastal hotel."},
            {"day": "Day 3", "title": "Horanadu Spiritual Route", "plan": "Proceed to Horanadu, visit the famous Annapoorneshwari Temple, and enjoy a peaceful evening."},
            {"day": "Day 4", "title": "Departure", "plan": "After morning prayers or temple time, depart to your selected drop-off point with a comfortable return transfer."},
        ],
        "cab_info": [
            "Private cab for temple transfers and pilgrim-friendly pacing.",
            "Support for local holy stops, travel timing, and luggage comfort.",
        ],
        "faq": [
            {"question": "Can I include darshan timing support?", "answer": "Yes. We can plan temple visits around preferred darshan slots and local temple schedules."},
            {"question": "Are vegetarian meals available?", "answer": "Yes. Vegetarian meals and local temple cuisine can be arranged at recommended stays."},
        ],
        "related_slugs": ["karnataka-tour-packages", "karnataka-beach-packages", "karnataka-temple-packages"],
    },
    "weekend-getaway-packages": {
        "slug": "weekend-getaway-packages",
        "title": "Weekend Getaway Packages",
        "theme": "Short Karnataka Escapes",
        "duration": "2 Days / 1 Night",
        "location": "Chikkamagaluru, Coorg",
        "image": "images/chikkamangalore-hero.jpeg",
        "summary": "Short Karnataka getaway packages perfect for weekend travellers seeking hills, coffee trails, and a fast refresh from city life.",
        "best_time": "September - May",
        "overview": "Designed for busy travellers, these packages provide quick scenic escapes with hill station breathing room and efficient private travel.",
        "why_choose": [
            "Ideal for short trips with minimal travel planning required.",
            "Work-friendly itineraries that balance relaxation and sightseeing.",
            "Quick return routes for weekend travellers leaving from Bangalore or Mysore.",
        ],
        "destinations": [
            {"title": "Chikkamagaluru Coffee Hills", "description": "A quick escape into rolling hills, coffee estates, and highland viewpoints."},
            {"title": "Coorg Serenity", "description": "Beautiful waterfalls, plantation walks, and calming hill resort stays."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-clock", "title": "Minimal Travel Time", "description": "Shorter routes and private cab support make the weekend escape efficient."},
            {"icon": "fa-solid fa-leaf", "title": "Natural Relaxation", "description": "Fresh mountain air and greenery create an instant refresh."},
            {"icon": "fa-solid fa-bed", "title": "Comfortable Stays", "description": "Handpicked accommodation for a comfortable one-night hill stop."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Drive to the Hills", "plan": "Depart early for Chikkamagaluru or Coorg, enjoy hill views, plantation walks, and a cozy evening stay."},
            {"day": "Day 2", "title": "Morning Sightseeing and Return", "plan": "Explore a scenic viewpoint, visit a coffee estate, then return to your city with a relaxed afternoon journey."},
        ],
        "cab_info": [
            "Weekend-ready cab with comfortable seating and luggage capacity.",
            "Flexible pickup from Bangalore or Mysore for quick hill departures.",
        ],
        "faq": [
            {"question": "Can I start this package from Bangalore?", "answer": "Yes. Weekend packages are designed with Bangalore pick-up and drop-off options."},
            {"question": "Is one night enough to enjoy the hills?", "answer": "Yes. The package focuses on the most scenic experiences to fit a short weekend trip."},
        ],
        "related_slugs": ["karnataka-hill-station-packages", "coffee-plantation-tours", "nature-eco-tourism-packages"],
    },
    "adventure-tour-packages": {
        "slug": "adventure-tour-packages",
        "title": "Adventure Tour Packages",
        "theme": "Active Karnataka",
        "duration": "3 Days / 2 Nights",
        "location": "Hampi, Chikkamagaluru",
        "image": "images/Hampi.jpeg",
        "summary": "Adventure-focused Karnataka packages featuring rugged ruins, hill treks, rock climbs, and energetic sightseeing.",
        "best_time": "October - February",
        "overview": "Adventure packages built for travellers who want active exploration, dramatic landscapes, and comfortable base stays within Karnataka.",
        "why_choose": [
            "Bold routes through Hampi’s boulder fields and hilltop viewpoints.",
            "Day plans that mix trekking with culture and scenic drives.",
            "Experienced cab travel for active travellers who value reliable routing.",
        ],
        "destinations": [
            {"title": "Hampi Rockscape", "description": "Explore dramatic ruins, heritage temples, and winding stone paths ideal for adventurous travellers."},
            {"title": "Chikkamagaluru Mountains", "description": "Trek to Mullayanagiri, visit coffee estates, and enjoy high-altitude adventure in the hills."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-hiking", "title": "Active Exploration", "description": "Trek, climb, and explore Karnataka’s most dramatic natural and built landscapes."},
            {"icon": "fa-solid fa-camera", "title": "Scenic Photography", "description": "Capture dramatic textures, sunrise views, and rugged heritage scenes."},
            {"icon": "fa-solid fa-route", "title": "Curated Adventure Routes", "description": "Routes designed for exploration while keeping travel practical and comfortable."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Hampi Adventure", "plan": "Arrive in Hampi, explore the heritage landscape, and enjoy sunset viewpoints over the river."},
            {"day": "Day 2", "title": "Hill Trek and Coffee", "plan": "Travel to Chikkamagaluru, trek the hill route, visit a coffee estate, and enjoy a rugged hill stay."},
            {"day": "Day 3", "title": "Return with Scenic Stops", "plan": "Explore a morning viewpoint, then return to your departure city with scenic stops along the way."},
        ],
        "cab_info": [
            "Adventure-ready cab with comfortable seating and route support.",
            "Experienced driver for rugged route timing and scenic stops.",
        ],
        "faq": [
            {"question": "Will this package include trekking?", "answer": "Yes. It includes easy to moderate trekking and scenic walks suitable for adventurous travellers."},
            {"question": "Is the route suitable for families?", "answer": "Yes, the package can be adapted for families with child-friendly stops and easier routes."},
        ],
        "related_slugs": ["karnataka-tour-packages", "karnataka-hill-station-packages", "coffee-plantation-tours"],
    },
    "coffee-plantation-tours": {
        "slug": "coffee-plantation-tours",
        "title": "Coffee Plantation Tours",
        "theme": "Coffee Country",
        "duration": "3 Days / 2 Nights",
        "location": "Chikkamagaluru, Coorg",
        "image": "images/Chikkamagaluru.jpeg",
        "summary": "Coffee plantation tours through Karnataka’s hill regions, with estate walks, farm stays, and coffee tasting experiences.",
        "best_time": "October - April",
        "overview": "Immerse yourself in Karnataka’s coffee country with guided plantation tours, estate stays, and private cab travel between green highland estates.",
        "why_choose": [
            "Direct access to premium coffee estates and tasting sessions.",
            "Comfortable hill station transfers and scenic estate routes.",
            "Relaxed pacing with nature-focused experiences in coffee country.",
        ],
        "destinations": [
            {"title": "Chikkamagaluru Estates", "description": "Discover sprawling coffee estates, plantation walks, and fresh local brews."},
            {"title": "Coorg Plantation Trails", "description": "Explore fragrant estates, spice gardens, and waterfall-adjacent routes in Coorg."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-mug-hot", "title": "Coffee Tasting", "description": "Sample freshly brewed coffee and learn the estate-to-cup process."},
            {"icon": "fa-solid fa-tree", "title": "Estate Walks", "description": "Enjoy quiet walks through lush plantations and shaded estate tracks."},
            {"icon": "fa-solid fa-leaf", "title": "Spice Garden Visits", "description": "Visit local spice gardens that complement the coffee country experience."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Coffee Estate Arrival", "plan": "Arrive in Chikkamagaluru, visit a coffee plantation, and enjoy a nature walk at the estate."},
            {"day": "Day 2", "title": "Estate Tours and Local Drinks", "plan": "Spend the day touring multiple estates, tasting coffee, and relaxing in the plantation surroundings."},
            {"day": "Day 3", "title": "Coorg and Departure", "plan": "Travel to Coorg, explore another coffee region, and depart with a scenic drive back."},
        ],
        "cab_info": [
            "Private cab for coffee country travel between estates.",
            "Local driver guidance for plantation and hill routes.",
        ],
        "faq": [
            {"question": "Can we visit multiple coffee estates?", "answer": "Yes. The package includes visits to at least two estates with guided tours and tastings."},
            {"question": "Is this package good for families?", "answer": "Yes. Plantation tours are family-friendly with gentle walks and scenic stops."},
        ],
        "related_slugs": ["karnataka-honeymoon-packages", "nature-eco-tourism-packages", "weekend-getaway-packages"],
    },
    "nature-eco-tourism-packages": {
        "slug": "nature-eco-tourism-packages",
        "title": "Nature & Eco Tourism Packages",
        "theme": "Green Karnataka",
        "duration": "3 Days / 2 Nights",
        "location": "Chikkamagaluru, Coorg",
        "image": "images/Hirekolale Lake.jpg",
        "summary": "Eco-friendly Karnataka packages focusing on sustainable nature experiences, lake visits, and forest edge trails.",
        "best_time": "September - February",
        "overview": "This eco tourism package highlights Karnataka’s greener side with low-impact travel, lakeside views, and nature conservation awareness.",
        "why_choose": [
            "Eco-conscious travel planning with nature-focused stays.",
            "Lake and plantation visits designed to minimize environmental impact.",
            "Private cab routes that prioritize scenic natural areas and quiet stops.",
        ],
        "destinations": [
            {"title": "Hirekolale Lake", "description": "A serene hill lake that offers calm nature photography and quiet walking trails."},
            {"title": "Coffee Forest Trails", "description": "Lush forest-like estates with eco-friendly trails and local biodiversity."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-seedling", "title": "Eco-Friendly Stays", "description": "Choose lodges and resorts with a focus on natural surroundings and sustainable comfort."},
            {"icon": "fa-solid fa-water", "title": "Lake Activities", "description": "Enjoy gentle lakeside strolls, birdwatching, and local nature views."},
            {"icon": "fa-solid fa-tree", "title": "Green Trails", "description": "Explore the calm side of Karnataka with quiet routes and forest-edge experiences."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Lake Arrival", "plan": "Arrive near Hirekolale Lake, enjoy a lakeside walk, and settle into a nature-friendly stay."},
            {"day": "Day 2", "title": "Forest and Plantation Trails", "plan": "Explore quiet trails, coffee estates, and eco-conscious local sites."},
            {"day": "Day 3", "title": "Return Journey", "plan": "Enjoy a calm morning, visit a hill viewpoint, and depart with scenic traveling."},
        ],
        "cab_info": [
            "Private cab for eco tourism routes and natural stops.",
            "Flexible timing for tranquil day plans and nature photo stops.",
        ],
        "faq": [
            {"question": "Are these activities low impact?", "answer": "Yes. The package focuses on low-impact experiences, quiet nature walks, and responsible travel."},
            {"question": "Can I book sustainable accommodation?", "answer": "Yes. The itinerary recommends stays with a nature-first approach and calm hill settings."},
        ],
        "related_slugs": ["karnataka-wildlife-packages", "coffee-plantation-tours", "weekend-getaway-packages"],
    },
    "family-holiday-packages": {
        "slug": "family-holiday-packages",
        "title": "Family Holiday Packages",
        "theme": "Karnataka Family Travel",
        "duration": "4 Days / 3 Nights",
        "location": "Mysore, Ooty, Coorg",
        "image": "images/mysore-hero.jpeg",
        "summary": "Family-friendly Karnataka packages that combine heritage, hill stations, and easy sightseeing with child-friendly travel support.",
        "best_time": "October - March",
        "overview": "Designed for families, this package balances cultural discovery, natural leisure, and relaxed cab travel across Karnataka.",
        "why_choose": [
            "Child-friendly itineraries with comfortable pacing.",
            "Private cab support for easy family transfers and sightseeing.",
            "A mix of heritage, nature, and light adventure suited for all ages.",
        ],
        "destinations": [
            {"title": "Mysore Palace", "description": "Royal heritage, gardens, and market experiences that families can enjoy together."},
            {"title": "Ooty Lakes", "description": "Calm lake walks, gardens, and easy hill station activities for children."},
            {"title": "Coorg Joy", "description": "Waterfalls, coffee estates, and gentle countryside drives that work well for families."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-child", "title": "Kid-Friendly Stops", "description": "Attractions chosen to keep children engaged and comfortable."},
            {"icon": "fa-solid fa-bus", "title": "Simple Transfers", "description": "Private cab service reduces transit stress for families."},
            {"icon": "fa-solid fa-people-group", "title": "Shared Memories", "description": "Balanced experiences for adults and children across heritage and nature."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Mysore Family Welcome", "plan": "Arrive in Mysore, visit the palace, and settle into a family-friendly hotel."},
            {"day": "Day 2", "title": "Ooty Hill Station", "plan": "Travel to Ooty, enjoy the lake, botanical gardens, and easy hill walks."},
            {"day": "Day 3", "title": "Coorg Waterfalls", "plan": "Visit Coorg for nature and waterfall experiences, staying in a comfortable resort."},
            {"day": "Day 4", "title": "Relax and Depart", "plan": "Enjoy a relaxed breakfast and return journey with scenic stops."},
        ],
        "cab_info": [
            "Family-friendly cab seating and flexible luggage handling.",
            "Private transfer support with child-friendly break planning.",
        ],
        "faq": [
            {"question": "Is this package suitable for young children?", "answer": "Yes. The itinerary is paced for families with children and includes easy sightseeing.", "answer": "Yes. The itinerary is paced for families with children and includes easy sightseeing."},
            {"question": "Can meal preferences be accommodated?", "answer": "Yes. Meal requests, including vegetarian and child-friendly options, can be arranged."},
        ],
        "related_slugs": ["karnataka-honeymoon-packages", "karnataka-beach-packages", "nature-eco-tourism-packages"],
    },
    "customized-karnataka-tours": {
        "slug": "customized-karnataka-tours",
        "title": "Customized Karnataka Tours",
        "theme": "Tailor-Made Travel",
        "duration": "Flexible Duration",
        "location": "Bangalore, Mysore, Coorg, Hampi",
        "image": "images/coorag.jpg",
        "summary": "Customized Karnataka tour planning for travellers who want a private itinerary shaped around their interests, schedule, and travel pace.",
        "best_time": "September - April",
        "overview": "Build the perfect Karnataka itinerary with special-request support for duration, hotels, attractions, private cab type, and travel style.",
        "why_choose": [
            "Fully customizable routes and hotel categories.",
            "Flexible cab type selection and pickup locations.",
            "Personalized travel pace for every group size.",
        ],
        "destinations": [
            {"title": "Bangalore Convenience", "description": "Start or end your tour from Bangalore with easy airport and city connections."},
            {"title": "Custom Karnataka Route", "description": "Choose the destinations that matter most to you, from heritage to hill stations and coastal escapes."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-pencil-ruler", "title": "Custom Route Planning", "description": "Design the route around your interests with help from the travel team."},
            {"icon": "fa-solid fa-car-side", "title": "Flexible Cab Options", "description": "Choose the cab type that fits your group, luggage, and budget."},
            {"icon": "fa-solid fa-star", "title": "Personalized Experience", "description": "Adjust every detail from hotel style to touring speed and meal preferences."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Consultation and Proposal", "plan": "Share your travel goals, preferred dates, and guest details. We prepare a tailored Karnataka route."},
            {"day": "Day 2", "title": "Route Confirmation", "plan": "Review the suggested itinerary, refine stops, and confirm accommodation and cab arrangements."},
            {"day": "Day 3", "title": "Travel Begins", "plan": "Begin the custom Karnataka journey with the confirmed route and support from the travel team."},
        ],
        "cab_info": [
            "Customized cab service to fit your itinerary and guest count.",
            "Cab selection support for sedan, SUV, or tempo traveller needs.",
        ],
        "faq": [
            {"question": "How much customization is possible?", "answer": "Almost everything can be customized, including duration, hotels, sightseeing stops, and cab type."},
            {"question": "Does this package include a personal itinerary planner?", "answer": "Yes. We help design your Karnataka itinerary based on your needs and preferences."},
        ],
        "related_slugs": ["karnataka-tour-packages", "exclusive-cab-packages", "family-holiday-packages"],
    },
    "exclusive-cab-packages": {
        "slug": "exclusive-cab-packages",
        "title": "Exclusive Cab Packages",
        "theme": "Private Road Travel",
        "duration": "Flexible",
        "location": "Bangalore, Karnataka Destinations",
        "image": "images/cabs/innova-realistic.jpeg",
        "summary": "Premium exclusive cab packages for personalized travel, airport transfers, and Karnataka sightseeing with a dedicated vehicle and driver.",
        "best_time": "Year Round",
        "overview": "Choose exclusive cab packages for private, convenient, and reliable travel across Karnataka, with flexible pickup, drop, and day tour options.",
        "why_choose": [
            "Dedicated cab exclusively reserved for your group.",
            "Comfortable transit with a captain-ready driver and route support.",
            "Ideal for private day tours, airport transfers, and multi-day trips.",
        ],
        "destinations": [
            {"title": "Airport and City Transfers", "description": "Seamless transfers from the airport or city to any Karnataka destination."},
            {"title": "Sightseeing Support", "description": "Flexible cab routing for day tours, temple visits, and nature excursions."},
        ],
        "highlights": [
            {"icon": "fa-solid fa-car", "title": "Exclusive Vehicle", "description": "A private cab reserved only for your travel group, with dedicated service."},
            {"icon": "fa-solid fa-route", "title": "Flexible Routing", "description": "Adjust the route and stops on the go within the package terms."},
            {"icon": "fa-solid fa-handshake", "title": "Reliable Service", "description": "Experienced drivers and transparent cab planning for peace of mind."},
        ],
        "itinerary": [
            {"day": "Day 1", "title": "Pickup and Onward Travel", "plan": "Begin with a comfortable pickup from the airport or city and proceed to your selected Karnataka destination."},
            {"day": "Day 2", "title": "Private Sightseeing", "plan": "Use your exclusive cab for curated sight tours, temple visits, or coastal drives as planned."},
            {"day": "Day 3", "title": "Return or Next Destination", "plan": "Complete your travel with a smooth drop-off at the next location or final departure point."},
        ],
        "cab_info": [
            "Dedicated exclusive cab for the full duration of your chosen package.",
            "Experienced driver with local route knowledge and timely service.",
        ],
        "faq": [
            {"question": "Is the cab available for day tours?", "answer": "Yes. Exclusive cab packages are ideal for day tours, multi-day routes, and airport transfers."},
            {"question": "Can I choose the type of cab?", "answer": "Yes. We offer cab options based on group size and comfort requirements."},
        ],
        "related_slugs": ["customized-karnataka-tours", "karnataka-tour-packages", "karnataka-hill-station-packages"],
    },
}


def get_karnataka_package(page_slug):
    package = KARNATAKA_PACKAGE_PAGES.get(page_slug)
    if not package:
        raise Http404("Karnataka package not found.")

    return {
        **package,
        "highlights": resolve_package_highlights(package),
        "image_url": safe_static_image(package["image"]),
    }


def curated_package_for_slug(package_slug):
    for package in curated_package_items():
        if package["slug"] == package_slug:
            return package

    if package_slug in KARNATAKA_PACKAGE_PAGES:
        return get_karnataka_package(package_slug)

    raise Http404("Holiday package not found.")


def gallery_location_key_for(filename):
    path_obj = Path(filename)
    parent_folder = path_obj.parent.name.lower()
    if parent_folder == "cabs":
        return "cab services"

    stem = path_obj.stem.lower()
    normalized_stem = stem.replace("_", "-")
    if normalized_stem in GALLERY_SPECIAL_FILES:
        return GALLERY_SPECIAL_FILES[normalized_stem]

    parts = [part for part in normalized_stem.split("-") if not part.isdigit()]
    if not parts:
        return "travel memories"

    base = parts[0].rstrip("0123456789")
    return GALLERY_NAME_FIXES.get(base, base)


def gallery_title_for(location_key):
    title = location_key.replace("-", " ").title()
    if not title:
        return "Travel Memories"
    return f"{title} Travel"


def gallery_image_item(image_path):
    relative_path = image_path.relative_to(settings.BASE_DIR / "static" / "images")
    location_key = gallery_location_key_for(relative_path)
    title = gallery_title_for(location_key)
    relative_url = str(relative_path).replace("\\", "/")
    return {
        "title": title,
        "location_key": location_key,
        "url": static(f"images/{relative_url}"),
        "alt": f"{title} image",
    }


def static_gallery_items():
    image_dir = settings.BASE_DIR / "static" / "images"
    if not image_dir.exists():
        return []

    items = []
    for image_path in sorted(image_dir.rglob("*"), key=lambda path: path.name.lower()):
        if not image_path.is_file():
            continue
        if image_path.name in GALLERY_EXCLUDES or image_path.suffix.lower() not in GALLERY_EXTENSIONS:
            continue
        items.append(gallery_image_item(image_path))
    return items


def gallery_group_sort_key(group):
    try:
        return (GALLERY_GROUP_ORDER.index(group["location_key"]), group["title"])
    except ValueError:
        return (len(GALLERY_GROUP_ORDER), group["title"])


def static_gallery_groups():
    groups = {}
    for item in static_gallery_items():
        location_key = item["location_key"]
        group = groups.setdefault(
            location_key,
            {
                "slug": location_key.replace(" ", "-"),
                "location_key": location_key,
                "title": gallery_title_for(location_key),
                "images": [],
            },
        )
        group["images"].append(item)

    grouped_items = []
    for group in groups.values():
        group["cover"] = group["images"][0]
        group["count"] = len(group["images"])
        grouped_items.append(group)
    return sorted(grouped_items, key=gallery_group_sort_key)


def static_gallery_group_for_slug(album_slug):
    for group in static_gallery_groups():
        if group["slug"] == album_slug:
            return group
    raise Http404("Gallery album not found.")


class ContactFormMixin:
    form_class = ContactEnquiryForm

    def get_form(self):
        return self.form_class(self.request.POST or None)

    def save_enquiry(self, form, success_url):
        form.save()
        messages.success(
            self.request,
            "Thank you! Your enquiry has been submitted successfully. Our travel expert will contact you shortly.",
        )
        return redirect(success_url)


def build_review_statistics():
    status_counts = CustomerReview.objects.aggregate(
        total=Count("id"),
        pending=Count("id", filter=Q(status=CustomerReview.Status.PENDING)),
        approved=Count("id", filter=Q(status=CustomerReview.Status.APPROVED)),
        rejected=Count("id", filter=Q(status=CustomerReview.Status.REJECTED)),
    )
    average_rating = float(CustomerReview.approved_average_rating() or 0)
    return {
        "total_reviews": status_counts["total"] or 0,
        "pending_reviews": status_counts["pending"] or 0,
        "approved_reviews": status_counts["approved"] or 0,
        "rejected_reviews": status_counts["rejected"] or 0,
        "average_rating": round(average_rating, 1),
    }


def format_review_response_errors(form):
    first_errors = []
    for field_errors in form.errors.values():
        if field_errors:
            first_errors.append(field_errors[0])
    return " ".join(first_errors) or "Please check the review form and try again."


class ReviewSubmitView(View):
    def post(self, request, *args, **kwargs):
        form = CustomerReviewForm(request.POST)

        if form.is_valid():
            cleaned = form.cleaned_data
            allowed = CustomerReview.can_accept_similar_submission(
                cleaned.get("name", ""),
                cleaned.get("email", ""),
                cleaned.get("review", ""),
            )

            if not allowed:
                return JsonResponse(
                    {
                        "success": False,
                        "message": "A similar review was submitted recently. Please wait a few minutes before trying again.",
                    },
                    status=429,
                )

            form.save()
            return JsonResponse(
                {
                    "success": True,
                    "message": "Thank you! Your review has been submitted successfully. It will appear after admin approval.",
                }
            )

        return JsonResponse(
            {
                "success": False,
                "message": format_review_response_errors(form),
            },
            status=400,
        )


class ReviewLikeView(View):
    def post(self, request, review_id, *args, **kwargs):
        updated = CustomerReview.objects.filter(
            pk=review_id,
            status=CustomerReview.Status.APPROVED,
        ).update(likes=F("likes") + 1)

        if not updated:
            return JsonResponse({"success": False, "message": "Review not found."}, status=404)

        likes = CustomerReview.objects.values_list("likes", flat=True).get(pk=review_id)
        return JsonResponse({"success": True, "likes": likes})


class WebsiteLikeView(View):
    def post(self, request, *args, **kwargs):
        visitor_token = (request.headers.get("X-Visitor-Like-Token") or "").strip()
        if not re.fullmatch(r"[a-zA-Z0-9_-]{12,64}", visitor_token):
            return JsonResponse(
                {
                    "success": False,
                    "message": "Invalid like token.",
                },
                status=400,
            )

        created, likes, like_version = WebsiteLikeCounter.register_visitor_like(visitor_token)
        if created:
            return JsonResponse(
                {
                    "success": True,
                    "likes": likes,
                    "already_liked": False,
                    "like_version": like_version,
                    "message": "Thank you for liking Aarya Holidays & Cabs ❤️",
                }
            )

        return JsonResponse(
            {
                "success": True,
                "likes": likes,
                "already_liked": True,
                "like_version": like_version,
                "message": "You have already liked this website.",
            }
        )


class HomeView(ContactFormMixin, TemplateView):
    template_name = "travel/home.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["form"] = self.get_form()
        context["featured_itineraries"] = curated_package_items()[:3]
        context["featured_cabs"] = CabService.objects.filter(
            is_active=True, is_featured=True
        )[:4]
        context["featured_destinations"] = Destination.objects.filter(
            is_active=True, is_featured=True
        )[:6]
        context["review_form"] = CustomerReviewForm(initial={"rating": 5})
        context["latest_approved_reviews"] = CustomerReview.approved()[:6]
        context["community_stats"] = {
            **build_review_statistics(),
            "total_visitors": VisitorCounter.load().total_count,
            "website_likes": WebsiteLikeCounter.load().total_likes,
        }
        return context

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            return self.save_enquiry(form, f"{reverse('travel:home')}#contact")

        context = self.get_context_data()
        context["form"] = form
        return self.render_to_response(context)


class AboutView(TemplateView):
    template_name = "travel/about.html"


class HolidayPackageListView(ListView):
    model = HolidayPackage
    template_name = "travel/packages.html"
    context_object_name = "packages"

    def get_queryset(self):
        return HolidayPackage.objects.filter(is_active=True)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["curated_packages"] = curated_package_items()
        context["old_site_tour_prices"] = [
            {**package, "image_url": safe_static_image(package["image"])}
            for package in OLD_SITE_TOUR_PRICES
        ]
        return context


class DomesticToursView(TemplateView):
    template_name = "travel/domestic_tours.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        domestic_packages = [
            package for package in curated_package_items()
            if package["slug"] not in INTERNATIONAL_PACKAGE_SLUGS
        ]
        context["domestic_packages"] = domestic_packages
        context["karnataka_feature"] = get_karnataka_package("karnataka-tour-packages")
        context["seo_meta"] = SimpleNamespace(
            title="Domestic Tours | Aarya Holidays & Cabs",
            description="Explore premium domestic tours across India, including hill stations, beach escapes, heritage routes, and family-friendly packages.",
            keywords="Domestic tours, India holiday packages, Aarya Holidays",
            canonical_url=self.request.build_absolute_uri(),
            robots="index,follow",
            og_image=domestic_packages[0]["image_url"] if domestic_packages else static("images/logo.jpeg"),
            site_name="Aarya Holidays & Cabs",
        )
        return context


class InternationalToursView(TemplateView):
    template_name = "travel/international_tours.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        international_packages = [
            package for package in curated_package_items()
            if package["slug"] in INTERNATIONAL_PACKAGE_SLUGS
        ]
        context["international_packages"] = international_packages
        context["seo_meta"] = SimpleNamespace(
            title="International Tours | Aarya Holidays & Cabs",
            description="Discover curated international tour packages with seamless planning, premium stays, and unforgettable global experiences.",
            keywords="International tours, global holiday packages, Aarya Holidays",
            canonical_url=self.request.build_absolute_uri(),
            robots="index,follow",
            og_image=international_packages[0]["image_url"] if international_packages else static("images/logo.jpeg"),
            site_name="Aarya Holidays & Cabs",
        )
        return context


class KarnatakaToursView(TemplateView):
    template_name = "travel/karnataka_tours.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        karnataka_packages = [get_karnataka_package(slug) for slug in KARNATAKA_PACKAGE_PAGES]
        context["karnataka_packages"] = karnataka_packages
        context["seo_meta"] = SimpleNamespace(
            title="Karnataka Tours | Aarya Holidays & Cabs",
            description="Browse our dedicated Karnataka tour packages with heritage, hill station, wildlife, beach, and pilgrimage experiences.",
            keywords="Karnataka tours, Karnataka holiday packages, Aarya Holidays",
            canonical_url=self.request.build_absolute_uri(),
            robots="index,follow",
            og_image=karnataka_packages[0]["image_url"] if karnataka_packages else static("images/logo.jpeg"),
            site_name="Aarya Holidays & Cabs",
        )
        return context


class KarnatakaTempleToursView(TemplateView):
    template_name = "travel/karnataka_temple_tours.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        temple_packages = karnataka_temple_tour_items()
        context["temple_tour_packages"] = temple_packages
        context["seo_meta"] = SimpleNamespace(
            title="Karnataka Temple Tours | Aarya Holidays & Cabs",
            description="Browse Karnataka Temple Tours itineraries with dedicated routes across Sringeri, Kollur, Udupi, Dharmasthala, Kukke, Gokarna, and Murudeshwar.",
            keywords="Karnataka temple tours, pilgrimage tours, Sringeri, Kollur, Udupi, Dharmasthala, Kukke",
            canonical_url=self.request.build_absolute_uri(),
            robots="index,follow",
            og_image=temple_packages[0]["image_url"] if temple_packages else static("images/logo.jpeg"),
            site_name="Aarya Holidays & Cabs",
        )
        return context


class KarnatakaTempleTourDetailView(TemplateView):
    template_name = "travel/karnataka_temple_tour_detail.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        package_slug = kwargs["itinerary_slug"]
        package = karnataka_temple_tour_for_slug(package_slug)
        context["package"] = package
        context["package_includes"] = COMMON_PACKAGE_INCLUDES
        context["package_excludes"] = COMMON_PACKAGE_EXCLUDES

        related_packages = [
            item for item in karnataka_temple_tour_items() if item["slug"] != package_slug
        ][:3]
        context["related_packages"] = related_packages
        context["seo_meta"] = SimpleNamespace(
            title=f"{package['title']} | Karnataka Temple Tours | Aarya Holidays & Cabs",
            description=package.get("summary", ""),
            keywords=", ".join(
                filter(None, [
                    package.get("title"),
                    package.get("theme"),
                    "Karnataka temple tours",
                    package.get("location"),
                ])
            ),
            canonical_url=self.request.build_absolute_uri(),
            robots="index,follow",
            og_image=package["image_url"],
            site_name="Aarya Holidays & Cabs",
        )
        return context


class HolidayPackageDetailView(TemplateView):
    template_name = "travel/package_detail.html"

    def get_template_names(self):
        package_slug = self.kwargs.get("package_slug", "")

        # Use custom templates for specific packages
        custom_templates = {
            "chikmagalur-tour-package": "travel/chikmagalur_package.html",
        }

        if package_slug in custom_templates:
            return [custom_templates[package_slug], self.template_name]

        return [self.template_name]

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        package_slug = kwargs["package_slug"]
        package = curated_package_for_slug(package_slug)
        context["package"] = package
        context["package_includes"] = COMMON_PACKAGE_INCLUDES
        context["package_excludes"] = COMMON_PACKAGE_EXCLUDES

        related_packages = []
        for slug in package.get("related_slugs", [])[:3]:
            try:
                if slug in KARNATAKA_PACKAGE_PAGES:
                    related_packages.append(get_karnataka_package(slug))
                else:
                    related_packages.append(curated_package_for_slug(slug))
            except Http404:
                continue

        if not related_packages:
            related_packages = [
                item for item in curated_package_items() if item["slug"] != package["slug"]
            ][:3]

        context["related_packages"] = related_packages
        context["seo_meta"] = SimpleNamespace(
            title=f"{package['title']} | Aarya Holidays & Cabs",
            description=package.get("summary", ""),
            keywords=", ".join(
                filter(None, [
                    package.get("title"),
                    package.get("theme"),
                    "Karnataka tour packages" if package["slug"].startswith("karnataka") else "Holiday packages",
                    package.get("location"),
                ])
            ),
            canonical_url=self.request.build_absolute_uri(),
            robots="index,follow",
            og_image=package["image_url"],
            site_name="Aarya Holidays & Cabs",
        )
        return context


class CabServiceListView(ListView):
    model = CabService
    template_name = "travel/cab_services.html"
    context_object_name = "cab_services"

    def get_queryset(self):
        return CabService.objects.filter(is_active=True)


class DestinationListView(ListView):
    model = Destination
    template_name = "travel/destinations.html"
    context_object_name = "destinations"

    def get_queryset(self):
        return Destination.objects.filter(is_active=True)


class GalleryListView(ListView):
    model = GalleryImage
    template_name = "travel/gallery.html"
    context_object_name = "gallery_images"

    def get_queryset(self):
        return GalleryImage.objects.filter(is_active=True)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["static_gallery_images"] = static_gallery_items()
        context["static_gallery_groups"] = static_gallery_groups()
        return context


class GalleryAlbumView(TemplateView):
    template_name = "travel/gallery_album.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        album = static_gallery_group_for_slug(kwargs["album_slug"])
        context["album"] = album
        context["other_albums"] = [
            group for group in static_gallery_groups() if group["slug"] != album["slug"]
        ]
        return context


class ContactView(FormView):
    template_name = "travel/contact.html"
    form_class = ContactEnquiryForm

    def get_success_url(self):
        return reverse("travel:contact")

    def form_valid(self, form):
        form.save()
        messages.success(
            self.request,
            "Thank you! Your enquiry has been submitted successfully. Our travel expert will contact you shortly.",
        )
        return super().form_valid(form)


class ReviewListView(TemplateView):
    template_name = "travel/reviews.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        search_query = (self.request.GET.get("q") or "").strip()
        sort_key = (self.request.GET.get("sort") or "newest").strip()

        queryset = CustomerReview.approved()
        if search_query:
            queryset = queryset.filter(
                Q(name__icontains=search_query)
                | Q(city__icontains=search_query)
                | Q(review__icontains=search_query)
            )

        if sort_key == "highest":
            queryset = queryset.order_by("-rating", "-created_at")
        else:
            sort_key = "newest"
            queryset = queryset.order_by("-created_at")

        paginator = Paginator(queryset, 9)
        page_obj = paginator.get_page(self.request.GET.get("page") or 1)

        stats = build_review_statistics()
        context.update(
            {
                "page_title": "Customer Reviews",
                "review_form": CustomerReviewForm(initial={"rating": 5}),
                "review_page_obj": page_obj,
                "review_search_query": search_query,
                "review_sort": sort_key,
                "average_rating": stats["average_rating"],
                "total_reviews": stats["approved_reviews"],
            }
        )
        return context
