"""
Notification service for sending push notifications for favorite products
"""
import asyncio
from typing import List, Optional, Dict, Any
from datetime import date, datetime, timedelta, time
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, or_
from sqlalchemy.orm import selectinload
import redis.asyncio as redis
import os
import json
import pytz

from app.models.user.user_model import User, UserAddress
from app.models.user.favorite_model import UserFavorite
from app.models.user.notification_model import UserNotification
from app.models.listing.products import ProductListing, Product
from app.models.staff.store_model import Store
from app.enums.enums import ListingStatusEnum, FavoriteDistanceUnitEnum
from app.utils.fcm import fcm_service
from app.services.user.customer_service import haversine_distance

# Redis connection for duplicate prevention
redis_client: Optional[redis.Redis] = None


async def save_notification_to_db(
    db: AsyncSession,
    user_id: int,
    title: str,
    body: str,
    notification_type: str,
    data_payload: Optional[Dict[str, Any]] = None,
    product_id: Optional[int] = None,
    store_id: Optional[int] = None,
    listing_id: Optional[int] = None,
    distance_km: Optional[float] = None,
    image_url: Optional[str] = None,
    fcm_sent: bool = False,
    fcm_error: Optional[str] = None
) -> UserNotification:
    """
    Save notification to database
    Returns the created notification record
    """
    notification = UserNotification(
        user_id=user_id,
        title=title,
        body=body,
        notification_type=notification_type,
        data_payload=data_payload or {},
        product_id=product_id,
        store_id=store_id,
        listing_id=listing_id,
        distance_km=distance_km,
        image_url=image_url,
        fcm_sent=fcm_sent,
        fcm_error=fcm_error,
        is_read=False
    )
    db.add(notification)
    await db.commit()
    await db.refresh(notification)
    return notification

async def get_redis_client() -> Optional[redis.Redis]:
    """Get or create Redis client"""
    global redis_client
    if redis_client is None:
        redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
        try:
            # Add socket timeout to prevent hanging
            redis_client = await redis.from_url(
                redis_url, 
                decode_responses=True,
                socket_connect_timeout=2,  # 2 second connection timeout
                socket_timeout=2,  # 2 second socket timeout
                retry_on_timeout=False
            )
            # Test connection with timeout
            await asyncio.wait_for(redis_client.ping(), timeout=2.0)
            print(f"✅ Redis connected successfully")
        except asyncio.TimeoutError:
            print(f"⚠️  Redis connection timeout. Continuing without duplicate prevention.")
            redis_client = None
            return None
        except Exception as e:
            print(f"⚠️  Redis not available: {e}. Continuing without duplicate prevention.")
            redis_client = None
            return None
    return redis_client


def convert_distance_to_km(distance_value: float, unit: FavoriteDistanceUnitEnum) -> float:
    """Convert distance to kilometers"""
    if unit == FavoriteDistanceUnitEnum.KILOMETERS:
        return distance_value
    elif unit == FavoriteDistanceUnitEnum.METERS:
        return distance_value / 1000.0
    elif unit == FavoriteDistanceUnitEnum.MILES:
        return distance_value * 1.60934
    return distance_value


async def check_and_send_favorite_notifications(
    db: AsyncSession,
        listing: ProductListing,
        store: Store
) -> None:
    """
    Check if any users have this product in favorites and send notifications
    Triggered when listing becomes APPROVED and go_live_date is reached
    """
    print(f"\n{'='*80}")
    print(f"NOTIFICATION CHECK STARTED")
    print(f"{'='*80}")
    print(f"Listing ID: {listing.listing_id}")
    print(f"Product ID: {listing.product_id}")
    print(f"Product Name: {listing.product.product_name if listing.product else 'N/A'}")
    print(f"Store ID: {store.store_id}")
    print(f"Store Name: {store.store_name}")
    print(f"Store Location: {store.store_location}")
    print(f"Store Coordinates: lat={store.latitude}, lng={store.longitude}")
    
    if not listing.product_id or not store.latitude or not store.longitude:
        print(f"❌ Notification check skipped: product_id={listing.product_id}, store_lat={store.latitude}, store_lng={store.longitude}")
        return
    
    # Get all users who have this product in favorites
    # First get all favorites with the product
    from app.models.listing.products import Product
    from app.models.user.favorite_model import user_favorite_products
    
    stmt = (
        select(UserFavorite)
        .options(
            selectinload(UserFavorite.user),
            selectinload(UserFavorite.products),
            selectinload(UserFavorite.addresses)
        )
        .join(user_favorite_products, UserFavorite.favorite_id == user_favorite_products.c.favorite_id)
        .where(
            and_(
                user_favorite_products.c.product_id == listing.product_id,
                UserFavorite.distance_value.isnot(None),
                UserFavorite.distance_unit.isnot(None)
            )
        )
    )
    
    result = await db.execute(stmt)
    favorites = result.scalars().all()
    
    print(f"\n📋 Found {len(favorites)} favorite(s) for product {listing.product_id}")
    print(f"{'-'*80}")
    
    notifications_to_send = []
    
    for idx, favorite in enumerate(favorites, 1):
        print(f"\n🔍 Processing Favorite #{idx} (ID: {favorite.favorite_id})")
        user = favorite.user
        if not user:
            print(f"  ❌ User not found for favorite {favorite.favorite_id}")
            continue
        
        print(f"  👤 User ID: {user.user_id}")
        print(f"  📧 User Email: {user.email}")
        print(f"  ✅ User Active: {user.is_active}")
        print(f"  📱 Device Token: {'✅ Set' if user.device_token else '❌ Missing'}")
        print(f"  🚗 Travel Mode Enabled: {favorite.travel_mode}")
        print(f"  🎯 User Travel Enabled: {user.is_travel_enabled if hasattr(user, 'is_travel_enabled') else 'N/A'}")
        print(f"  📍 User Current Location: lat={user.latitude}, lng={user.longitude}" if user.latitude and user.longitude else "  📍 User Current Location: ❌ Not set")
        
        if not user.device_token:
            print(f"  ⚠️  SKIPPED: User {user.user_id} has no device_token")
            continue
        if not user.is_active:
            print(f"  ⚠️  SKIPPED: User {user.user_id} is not active")
            continue
        
        # Convert favorite distance to km
        radius_km = convert_distance_to_km(
            favorite.distance_value,
            favorite.distance_unit
        )
        print(f"  📏 Radius: {favorite.distance_value} {favorite.distance_unit.value} ({radius_km:.2f} km)")
        print(f"  📍 Addresses linked: {len(favorite.addresses)}")
        
        # Always check address-based notifications (regardless of travel_mode)
        # Users can have both address-based and travel mode notifications
        address_notifications = 0
        for addr_idx, address in enumerate(favorite.addresses, 1):
            print(f"\n    🏠 Address #{addr_idx} (ID: {address.address_id})")
            print(f"      Label: {address.label}")
            print(f"      Location: lat={address.latitude}, lng={address.longitude}")
            
            if not address.latitude or not address.longitude:
                print(f"      ⚠️  SKIPPED: Address missing coordinates")
                continue
            
            distance = haversine_distance(
                                address.latitude,
                                address.longitude,
                                store.latitude,
                                store.longitude
                            )
                            
            print(f"      📐 Distance to store: {distance:.2f} km")
            print(f"      📏 Radius limit: {radius_km:.2f} km")
            
            if distance <= radius_km:
                print(f"      ✅ WITHIN RADIUS! (distance {distance:.2f} km <= radius {radius_km:.2f} km)")
                
                # Check for duplicate notification
                redis_client = await get_redis_client()
                notification_key = f"notif:{user.user_id}:product:{listing.product_id}:store:{store.store_id}:address:{address.address_id}"
                
                if redis_client:
                    try:
                        already_notified = await redis_client.get(notification_key)
                        if already_notified:
                            print(f"      ⚠️  SKIPPED: Duplicate notification (already sent in last 24h)")
                            continue
                        # Set notification sent flag (24 hour TTL)
                        await redis_client.setex(notification_key, 86400, "1")
                        print(f"      🔒 Set duplicate prevention key: {notification_key}")
                    except Exception as e:
                        print(f"      ⚠️  Redis error (continuing anyway): {e}")
                else:
                    print(f"      ⚠️  Redis not available - skipping duplicate check")
                
                # Format distance - use 2 decimal places for small distances
                if favorite.distance_unit == FavoriteDistanceUnitEnum.METERS:
                    distance_str = f"{distance * 1000:.0f} meters"
                elif favorite.distance_unit == FavoriteDistanceUnitEnum.MILES:
                    distance_str = f"{distance / 1.60934:.1f} miles"
                else:
                    # Use 2 decimal places for distances < 1 km for better precision
                    if distance < 1.0:
                        distance_str = f"{distance:.2f} km"
                    else:
                        distance_str = f"{distance:.1f} km"
                
                address_label = address.label or "your location"
                
                title = "Favorite Product Available!"
                body = f"{listing.product.product_name} is available at {store.store_name}, {distance_str} from {address_label}"
                
                print(f"      📤 ADDING NOTIFICATION:")
                print(f"         Title: {title}")
                print(f"         Body: {body}")
                
                notifications_to_send.append({
                    "user_id": user.user_id,
                    "device_token": user.device_token,
                    "title": title,
                    "body": body,
                    "data": {
                        "type": "favorite_product",
                        "product_id": str(listing.product_id),
                        "store_id": str(store.store_id),
                        "listing_id": str(listing.listing_id),
                        "address_id": str(address.address_id),
                        "distance": str(distance)
                    },
                    "image_url": listing.product.product_image
                })
                address_notifications += 1
            else:
                print(f"      ❌ OUTSIDE RADIUS (distance {distance:.2f} km > radius {radius_km:.2f} km)")
        
        if address_notifications > 0:
            print(f"  ✅ Added {address_notifications} address-based notification(s)")
        
        # Check travel mode notifications (only if travel_mode is enabled in favorite)
        print(f"\n    🚗 Travel Mode Check:")
        if not favorite.travel_mode:
            print(f"      ⚠️  SKIPPED: Travel mode not enabled in favorite")
        elif not user.is_travel_enabled:
            print(f"      ⚠️  SKIPPED: User travel mode not enabled")
        elif not user.latitude or not user.longitude:
            print(f"      ⚠️  SKIPPED: User current location not set")
        else:
            distance = haversine_distance(
                            user.latitude,
                            user.longitude,
                            store.latitude,
                            store.longitude
                        )
                        
            print(f"      📐 Distance to store: {distance:.2f} km")
            print(f"      📏 Radius limit: {radius_km:.2f} km")
            
            if distance <= radius_km:
                print(f"      ✅ WITHIN RADIUS! (distance {distance:.2f} km <= radius {radius_km:.2f} km)")
                
                # Check for duplicate notification
                redis_client = await get_redis_client()
                notification_key = f"notif:{user.user_id}:product:{listing.product_id}:store:{store.store_id}:travel"
                
                if redis_client:
                    try:
                        already_notified = await redis_client.get(notification_key)
                        if already_notified:
                            print(f"      ⚠️  SKIPPED: Duplicate notification (already sent in last 24h)")
                        else:
                            # Set notification sent flag (24 hour TTL)
                            await redis_client.setex(notification_key, 86400, "1")
                            print(f"      🔒 Set duplicate prevention key: {notification_key}")
                    except Exception as e:
                        print(f"      ⚠️  Redis error (continuing anyway): {e}")
                else:
                    print(f"      ⚠️  Redis not available - skipping duplicate check")
                
                # Format distance
                if favorite.distance_unit == FavoriteDistanceUnitEnum.METERS:
                    distance_str = f"{distance * 1000:.0f} meters"
                elif favorite.distance_unit == FavoriteDistanceUnitEnum.MILES:
                    distance_str = f"{distance / 1.60934:.1f} miles"
                else:
                    # Use 2 decimal places for distances < 1 km for better precision
                    if distance < 1.0:
                        distance_str = f"{distance:.2f} km"
                    else:
                        distance_str = f"{distance:.1f} km"
                
                title = "Favorite Product Nearby!"
                body = f"{listing.product.product_name} is available at {store.store_name}, {distance_str} away"
                
                print(f"      📤 ADDING NOTIFICATION:")
                print(f"         Title: {title}")
                print(f"         Body: {body}")
                
                notifications_to_send.append({
                    "user_id": user.user_id,
                    "device_token": user.device_token,
                    "title": title,
                    "body": body,
                    "data": {
                        "type": "favorite_product_travel",
                        "product_id": str(listing.product_id),
                        "store_id": str(store.store_id),
                        "listing_id": str(listing.listing_id),
                        "distance": str(distance)
                    },
                    "image_url": listing.product.product_image
                })
            else:
                print(f"      ❌ OUTSIDE RADIUS (distance {distance:.2f} km > radius {radius_km:.2f} km)")
    
    # Send all notifications
    print(f"\n{'='*80}")
    print(f"📊 NOTIFICATION SUMMARY")
    print(f"{'='*80}")
    print(f"Total notifications to send: {len(notifications_to_send)}")
    
    if notifications_to_send:
        print(f"\n📤 Sending {len(notifications_to_send)} notification(s)...")
        # Send notifications concurrently
        tasks = []
        for idx, notif in enumerate(notifications_to_send, 1):
            print(f"  [{idx}/{len(notifications_to_send)}] Sending to device token: {notif['device_token'][:20]}...")
            
            # Save notification to database first
            try:
                saved_notification = await save_notification_to_db(
                    db=db,
                    user_id=notif["user_id"],
                    title=notif["title"],
                    body=notif["body"],
                    notification_type=notif["data"].get("type", "unknown"),
                    data_payload=notif["data"],
                    product_id=int(notif["data"].get("product_id")) if notif["data"].get("product_id") else None,
                    store_id=int(notif["data"].get("store_id")) if notif["data"].get("store_id") else None,
                    listing_id=int(notif["data"].get("listing_id")) if notif["data"].get("listing_id") else None,
                    distance_km=float(notif["data"].get("distance")) if notif["data"].get("distance") else None,
                    image_url=notif.get("image_url"),
                    fcm_sent=False,  # Will update after FCM send
                    fcm_error=None
                )
                print(f"      ✅ Saved to database (notification_id: {saved_notification.notification_id})")
            except Exception as e:
                print(f"      ⚠️  Failed to save to database: {e}")
                saved_notification = None
            
            # Create task to send FCM notification and update DB
            async def send_and_update_notif(n, saved_notif):
                fcm_success = False
                fcm_error_msg = None
                try:
                    fcm_success = await fcm_service.send_notification(
                        device_token=n["device_token"],
                        title=n["title"],
                        body=n["body"],
                        data=n.get("data"),
                        image_url=n.get("image_url")
                    )
                    if not fcm_success:
                        fcm_error_msg = "FCM returned False"
                except Exception as e:
                    fcm_error_msg = str(e)
                
                # Update notification in database with FCM result
                if saved_notif:
                    try:
                        saved_notif.fcm_sent = fcm_success
                        saved_notif.fcm_error = fcm_error_msg
                        await db.commit()
                    except Exception as e:
                        print(f"      ⚠️  Failed to update notification in database: {e}")
                
                return fcm_success
            
            tasks.append(send_and_update_notif(notif, saved_notification))
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        sent_count = len([r for r in results if r is True])
        failed_count = len([r for r in results if r is False])
        error_count = len([r for r in results if isinstance(r, Exception)])
        
        print(f"\n✅ Results:")
        print(f"   ✅ Successfully sent: {sent_count}")
        print(f"   ❌ Failed: {failed_count}")
        print(f"   ⚠️  Errors: {error_count}")
        
        if error_count > 0:
            print(f"\n⚠️  Error details:")
            for i, r in enumerate(results, 1):
                if isinstance(r, Exception):
                    print(f"   [{i}] {type(r).__name__}: {str(r)}")
    else:
        print(f"⚠️  No notifications to send")
    
    print(f"{'='*80}")
    print(f"NOTIFICATION CHECK COMPLETED")
    print(f"{'='*80}\n")


async def check_travel_mode_notifications(
    db: AsyncSession,
    user_id: int
) -> None:
    """
    Check if user's current location is within radius of stores with favorite products
    Called when user updates location (every 10-15 seconds)
        """
    print(f"\n🔔 TRAVEL MODE NOTIFICATION CHECK - User {user_id}")
    
    # Get user with favorites
    stmt = (
            select(User)
            .options(
                selectinload(User.favorites).selectinload(UserFavorite.products),
                selectinload(User.favorites).selectinload(UserFavorite.addresses)
            )
            .where(User.user_id == user_id)
        )
    
    result = await db.execute(stmt)
    user = result.scalar_one_or_none()
    
    if not user:
        print(f"   ❌ User {user_id} not found - Skipping")
        return
    
    if not user.is_travel_enabled:
        print(f"   ⏸️  Travel mode is DISABLED for user {user_id} - Skipping")
        return
    
    if not user.latitude or not user.longitude:
        print(f"   ⚠️  User {user_id} location not set (lat: {user.latitude}, lon: {user.longitude}) - Skipping")
        return
    
    if not user.device_token:
        print(f"   ⚠️  User {user_id} has no device token - Skipping")
        return
    
    print(f"   ✅ User {user_id} - Travel Mode: ENABLED")
    print(f"   📍 User Location: ({user.latitude}, {user.longitude})")
    print(f"   📱 Device Token: {'✅ Set' if user.device_token else '❌ Missing'}")
    
    # Get all active listings with go_live_date <= today (using UTC)
    # go_live_date is stored in UTC, so we compare against UTC date
    from datetime import timezone
    from datetime import datetime as dt
    today_utc = dt.now(timezone.utc).date()
    listings_stmt = (
        select(ProductListing)
        .options(
            selectinload(ProductListing.product),
            selectinload(ProductListing.store)
        )
        .join(Store)
        .where(
            and_(
                ProductListing.status == ListingStatusEnum.APPROVED,
                ProductListing.go_live_date <= today_utc,
                Store.latitude.isnot(None),
                Store.longitude.isnot(None)
            )
        )
    )
    
    listings_result = await db.execute(listings_stmt)
    listings = listings_result.scalars().all()
    
    print(f"   📦 Found {len(listings)} active listings (go_live_date <= {today_utc})")
    print(f"   ❤️  User has {len(user.favorites)} favorite(s)")
    
    notifications_to_send = []
    
    # Check each favorite (only those with travel_mode enabled)
    for favorite_idx, favorite in enumerate(user.favorites, 1):
        print(f"\n   🔍 Checking Favorite #{favorite_idx}:")
        
        # Skip if travel_mode is not enabled for this favorite
        if not favorite.travel_mode:
            print(f"      ⏸️  Travel mode DISABLED for this favorite - Skipping")
            continue
        
        if not favorite.distance_value or not favorite.distance_unit:
            print(f"      ⚠️  Distance not set (value: {favorite.distance_value}, unit: {favorite.distance_unit}) - Skipping")
            continue
        
        radius_km = convert_distance_to_km(
            favorite.distance_value,
            favorite.distance_unit
        )
        
        product_names = [p.product_name for p in favorite.products]
        print(f"      ✅ Travel mode ENABLED")
        print(f"      📏 Radius: {favorite.distance_value} {favorite.distance_unit} ({radius_km:.2f} km)")
        print(f"      🛍️  Products in favorite: {len(favorite.products)} - {', '.join(product_names[:3])}{'...' if len(product_names) > 3 else ''}")
        
        # Check each listing
        matches_found = 0
        for listing in listings:
            # Check if user has this product in favorites
            product_ids = [p.product_id for p in favorite.products]
            if listing.product_id not in product_ids:
                continue
            
            store = listing.store
            if not store.latitude or not store.longitude:
                continue
            
            distance = haversine_distance(
                user.latitude,
                user.longitude,
                store.latitude,
                store.longitude
            )
            
            print(f"         📍 Product: {listing.product.product_name} at {store.store_name}")
            print(f"            User coords: ({user.latitude}, {user.longitude})")
            print(f"            Store coords: ({store.latitude}, {store.longitude})")
            print(f"            Distance: {distance:.2f} km (radius: {radius_km:.2f} km)")
            
            if distance <= radius_km:
                matches_found += 1
                print(f"            ✅ WITHIN RADIUS! (Match #{matches_found})")
                
                # Check for duplicate notification
                redis_client = await get_redis_client()
                notification_key = f"notif:{user.user_id}:product:{listing.product_id}:store:{store.store_id}:travel"
                
                if redis_client:
                    try:
                        already_notified = await redis_client.get(notification_key)
                        if already_notified:
                            print(f"            ⏭️  Already notified (Redis cache) - Skipping duplicate")
                            continue
                        # Set notification sent flag (24 hour TTL)
                        await redis_client.setex(notification_key, 86400, "1")
                        print(f"            💾 Cached in Redis (24h TTL)")
                    except Exception as e:
                        print(f"            ⚠️  Redis error (continuing anyway): {e}")
                else:
                    print(f"            ⚠️  Redis not available - No duplicate prevention")
                
                # Format distance
                if favorite.distance_unit == FavoriteDistanceUnitEnum.METERS:
                    distance_str = f"{distance * 1000:.0f} meters"
                elif favorite.distance_unit == FavoriteDistanceUnitEnum.MILES:
                    distance_str = f"{distance / 1.60934:.1f} miles"
                else:
                    # Use 2 decimal places for distances < 1 km for better precision
                    if distance < 1.0:
                        distance_str = f"{distance:.2f} km"
                    else:
                        distance_str = f"{distance:.1f} km"
                
                title = "Favorite Product Nearby!"
                body = f"{listing.product.product_name} is available at {store.store_name}, {distance_str} away"
                
                notifications_to_send.append({
                    "user_id": user.user_id,
                    "device_token": user.device_token,
                    "title": title,
                    "body": body,
                    "data": {
                        "type": "favorite_product_travel",
                        "product_id": str(listing.product_id),
                        "store_id": str(store.store_id),
                        "listing_id": str(listing.listing_id),
                        "distance": str(distance)
                    },
                    "image_url": listing.product.product_image
                })
                print(f"            📤 Added to notification queue: {title}")
        
        if matches_found == 0:
            print(f"      ℹ️  No products within radius for this favorite")
    
    # Send all notifications and save to database
    if notifications_to_send:
        print(f"\n   📤 Sending {len(notifications_to_send)} travel mode notification(s)...")
        tasks = []
        for idx, notif in enumerate(notifications_to_send, 1):
            # Save notification to database first
            try:
                saved_notification = await save_notification_to_db(
                    db=db,
                    user_id=notif["user_id"],
                    title=notif["title"],
                    body=notif["body"],
                    notification_type=notif["data"].get("type", "unknown"),
                    data_payload=notif["data"],
                    product_id=int(notif["data"].get("product_id")) if notif["data"].get("product_id") else None,
                    store_id=int(notif["data"].get("store_id")) if notif["data"].get("store_id") else None,
                    listing_id=int(notif["data"].get("listing_id")) if notif["data"].get("listing_id") else None,
                    distance_km=float(notif["data"].get("distance")) if notif["data"].get("distance") else None,
                    image_url=notif.get("image_url"),
                    fcm_sent=False,
                    fcm_error=None
                )
                print(f"  [{idx}/{len(notifications_to_send)}] ✅ Saved to database (notification_id: {saved_notification.notification_id})")
            except Exception as e:
                print(f"  [{idx}/{len(notifications_to_send)}] ⚠️  Failed to save to database: {e}")
                saved_notification = None
            
            # Create task to send FCM notification and update DB
            async def send_and_update_notif(n, saved_notif):
                fcm_success = False
                fcm_error_msg = None
                try:
                    fcm_success = await fcm_service.send_notification(
                        device_token=n["device_token"],
                        title=n["title"],
                        body=n["body"],
                        data=n.get("data"),
                        image_url=n.get("image_url")
                    )
                    if not fcm_success:
                        fcm_error_msg = "FCM returned False"
                except Exception as e:
                    fcm_error_msg = str(e)
                
                # Update notification in database with FCM result
                if saved_notif:
                    try:
                        saved_notif.fcm_sent = fcm_success
                        saved_notif.fcm_error = fcm_error_msg
                        await db.commit()
                    except Exception as e:
                        print(f"      ⚠️  Failed to update notification in database: {e}")
                
                return fcm_success
            
            tasks.append(send_and_update_notif(notif, saved_notification))
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        sent_count = len([r for r in results if r is True])
        print(f"   ✅ Sent {sent_count}/{len(notifications_to_send)} travel mode notifications for user {user_id}")
        print(f"   📊 Summary: {sent_count} sent, {len(notifications_to_send) - sent_count} failed")
    else:
        print(f"   ℹ️  No notifications to send - No products within radius")
    
    print(f"🔔 TRAVEL MODE CHECK COMPLETE - User {user_id}\n")


def is_notification_time(user_timezone: Optional[str], notification_hour: int = 20, notification_minute: int = 0) -> bool:
    """
    Check if current time in user's timezone matches the notification time
    Returns True if it's time to send notification, False otherwise
    
    Args:
        user_timezone: IANA timezone string (e.g., 'America/New_York', 'Europe/London')
        notification_hour: Hour to send notification (0-23), default 20 (8 PM)
        notification_minute: Minute to send notification (0-59), default 0
    """
    try:
        if user_timezone:
            # Get current time in user's timezone
            tz = pytz.timezone(user_timezone)
            user_now = datetime.now(tz)
        else:
            # Fallback to UTC if timezone not set
            tz = pytz.UTC
            user_now = datetime.now(tz)
        
        # Check if current time is within 5 minutes of notification time
        # This allows for slight variations in cron execution time
        current_hour = user_now.hour
        current_minute = user_now.minute
        
        # Calculate total minutes from midnight for both times
        current_total_minutes = current_hour * 60 + current_minute
        target_total_minutes = notification_hour * 60 + notification_minute
        
        # Calculate difference (handle day wrap-around)
        diff_minutes = abs(current_total_minutes - target_total_minutes)
        # Also check wrap-around case (e.g., 23:55 vs 00:05)
        diff_minutes = min(diff_minutes, 1440 - diff_minutes)
        
        # Send if within 5 minutes of target time
        return diff_minutes <= 5
    except Exception as e:
        print(f"Error checking timezone {user_timezone}: {str(e)}")
        # On error, default to sending (to avoid missing notifications)
        return True


async def check_and_send_favorite_notifications_with_timezone(
    db: AsyncSession,
    listing: ProductListing,
    store: Store,
    notification_hour: int = 20,
    notification_minute: int = 0
) -> None:
    """
    Check if any users have this product in favorites and send notifications
    Only sends if it's the notification time in the user's timezone
    
    Args:
        db: Database session
        listing: Product listing that went live
        store: Store where listing is available
        notification_hour: Hour to send notification (0-23), default 20 (8 PM)
        notification_minute: Minute to send notification (0-59), default 0
    """
    if not listing.product_id or not store.latitude or not store.longitude:
        return
    
    # Get all users who have this product in favorites
    from app.models.user.favorite_model import user_favorite_products
    
    stmt = (
        select(UserFavorite)
        .options(
            selectinload(UserFavorite.user),
            selectinload(UserFavorite.products),
            selectinload(UserFavorite.addresses)
        )
        .join(user_favorite_products, UserFavorite.favorite_id == user_favorite_products.c.favorite_id)
        .where(
            and_(
                user_favorite_products.c.product_id == listing.product_id,
                UserFavorite.distance_value.isnot(None),
                UserFavorite.distance_unit.isnot(None)
            )
        )
    )
    
    result = await db.execute(stmt)
    favorites = result.scalars().all()
    
    notifications_to_send = []
    
    for favorite in favorites:
        user = favorite.user
        if not user or not user.device_token or not user.is_active:
            continue
        
        # Check if it's notification time in user's timezone
        if not is_notification_time(user.timezone, notification_hour, notification_minute):
            continue
        
        # Convert favorite distance to km
        radius_km = convert_distance_to_km(
            favorite.distance_value,
            favorite.distance_unit
        )
        
        # Check address-based notifications (if travel_mode is False or not set)
        if not favorite.travel_mode:
            # Check all addresses linked to this favorite
            for address in favorite.addresses:
                if address.latitude and address.longitude:
                    distance = haversine_distance(
                        address.latitude,
                        address.longitude,
                        store.latitude,
                        store.longitude
                    )
                    
                    if distance <= radius_km:
                        # Check for duplicate notification
                        redis_client = await get_redis_client()
                        notification_key = f"notif:{user.user_id}:product:{listing.product_id}:store:{store.store_id}:address:{address.address_id}"
                        
                        if redis_client:
                            try:
                                already_notified = await redis_client.get(notification_key)
                                if already_notified:
                                    continue
                                # Set notification sent flag (24 hour TTL)
                                await redis_client.setex(notification_key, 86400, "1")
                            except Exception as e:
                                print(f"      ⚠️  Redis error (continuing anyway): {e}")
                        
                        # Format distance - use 2 decimal places for small distances
                        if favorite.distance_unit == FavoriteDistanceUnitEnum.METERS:
                            distance_str = f"{distance * 1000:.0f} meters"
                        elif favorite.distance_unit == FavoriteDistanceUnitEnum.MILES:
                            distance_str = f"{distance / 1.60934:.1f} miles"
                        else:
                            # Use 2 decimal places for distances < 1 km for better precision
                            if distance < 1.0:
                                distance_str = f"{distance:.2f} km"
                            else:
                                distance_str = f"{distance:.1f} km"
                        
                        address_label = address.label or "your location"
                        
                        title = "Favorite Product Available!"
                        body = f"{listing.product.product_name} is available at {store.store_name}, {distance_str} from {address_label}"
                        
                        notifications_to_send.append({
                            "user_id": user.user_id,
                            "device_token": user.device_token,
                            "title": title,
                            "body": body,
                            "data": {
                                "type": "favorite_product",
                                "product_id": str(listing.product_id),
                                "store_id": str(store.store_id),
                                "listing_id": str(listing.listing_id),
                                "address_id": str(address.address_id),
                                "distance": str(distance)
                            },
                            "image_url": listing.product.product_image
                        })
        
        # Check travel mode notifications
        if user.is_travel_enabled and user.latitude and user.longitude:
            distance = haversine_distance(
                user.latitude,
                user.longitude,
                store.latitude,
                store.longitude
            )
            
            if distance <= radius_km:
                # Check for duplicate notification
                redis_client = await get_redis_client()
                notification_key = f"notif:{user.user_id}:product:{listing.product_id}:store:{store.store_id}:travel"
                
                if redis_client:
                    try:
                        already_notified = await redis_client.get(notification_key)
                        if already_notified:
                            continue
                        # Set notification sent flag (24 hour TTL)
                        await redis_client.setex(notification_key, 86400, "1")
                    except Exception as e:
                        print(f"      ⚠️  Redis error (continuing anyway): {e}")
                
                # Format distance
                if favorite.distance_unit == FavoriteDistanceUnitEnum.METERS:
                    distance_str = f"{distance * 1000:.0f} meters"
                elif favorite.distance_unit == FavoriteDistanceUnitEnum.MILES:
                    distance_str = f"{distance / 1.60934:.1f} miles"
                else:
                    # Use 2 decimal places for distances < 1 km for better precision
                    if distance < 1.0:
                        distance_str = f"{distance:.2f} km"
                    else:
                        distance_str = f"{distance:.1f} km"
                
                title = "Favorite Product Nearby!"
                body = f"{listing.product.product_name} is available at {store.store_name}, {distance_str} away"
                
                notifications_to_send.append({
                    "user_id": user.user_id,
                    "device_token": user.device_token,
                    "title": title,
                    "body": body,
                    "data": {
                        "type": "favorite_product_travel",
                        "product_id": str(listing.product_id),
                        "store_id": str(store.store_id),
                        "listing_id": str(listing.listing_id),
                        "distance": str(distance)
                    },
                    "image_url": listing.product.product_image
                })
    
    # Send all notifications and save to database
    if notifications_to_send:
        print(f"\n📤 Sending {len(notifications_to_send)} timezone-aware notification(s)...")
        tasks = []
        for idx, notif in enumerate(notifications_to_send, 1):
            # Save notification to database first
            try:
                saved_notification = await save_notification_to_db(
                    db=db,
                    user_id=notif["user_id"],
                    title=notif["title"],
                    body=notif["body"],
                    notification_type=notif["data"].get("type", "unknown"),
                    data_payload=notif["data"],
                    product_id=int(notif["data"].get("product_id")) if notif["data"].get("product_id") else None,
                    store_id=int(notif["data"].get("store_id")) if notif["data"].get("store_id") else None,
                    listing_id=int(notif["data"].get("listing_id")) if notif["data"].get("listing_id") else None,
                    distance_km=float(notif["data"].get("distance")) if notif["data"].get("distance") else None,
                    image_url=notif.get("image_url"),
                    fcm_sent=False,
                    fcm_error=None
                )
                print(f"  [{idx}/{len(notifications_to_send)}] ✅ Saved to database (notification_id: {saved_notification.notification_id})")
            except Exception as e:
                print(f"  [{idx}/{len(notifications_to_send)}] ⚠️  Failed to save to database: {e}")
                saved_notification = None
            
            # Create task to send FCM notification and update DB
            async def send_and_update_notif(n, saved_notif):
                fcm_success = False
                fcm_error_msg = None
                try:
                    fcm_success = await fcm_service.send_notification(
                        device_token=n["device_token"],
                        title=n["title"],
                        body=n["body"],
                        data=n.get("data"),
                        image_url=n.get("image_url")
                    )
                    if not fcm_success:
                        fcm_error_msg = "FCM returned False"
                except Exception as e:
                    fcm_error_msg = str(e)
                
                # Update notification in database with FCM result
                if saved_notif:
                    try:
                        saved_notif.fcm_sent = fcm_success
                        saved_notif.fcm_error = fcm_error_msg
                        await db.commit()
                    except Exception as e:
                        print(f"      ⚠️  Failed to update notification in database: {e}")
                
                return fcm_success
            
            tasks.append(send_and_update_notif(notif, saved_notification))
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        sent_count = len([r for r in results if r is True])
        print(f"✅ Sent {sent_count}/{len(notifications_to_send)} timezone-aware notifications for listing {listing.listing_id}")
