"""
Cron job service for checking go_live_date and sending notifications
Run this hourly to check listings and send notifications at the right time for each user's timezone
"""
from datetime import date, datetime, time
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy import select, and_, or_
from sqlalchemy.orm import selectinload
import os
from dotenv import load_dotenv
import pytz

from app.models.listing.products import ProductListing
from app.models.staff.store_model import Store
from app.models.user.user_model import User
from app.models.user.favorite_model import UserFavorite, user_favorite_products
from app.enums.enums import ListingStatusEnum
from app.services.user.notification_service import check_and_send_favorite_notifications_with_timezone
from app.database.database import DATABASE_URL

load_dotenv()

# Default notification time: 8:00 PM (20:00)
NOTIFICATION_HOUR = int(os.getenv("NOTIFICATION_HOUR", "20"))
NOTIFICATION_MINUTE = int(os.getenv("NOTIFICATION_MINUTE", "0"))


async def check_go_live_listings():
    """
    Check all listings where go_live_date is today (in UTC) and status is APPROVED
    Send notifications to users who have those products in favorites
    Only sends if it's the configured notification time (default 8:00 PM) in the user's timezone
    """
    # Create database session
    engine = create_async_engine(DATABASE_URL, echo=False)
    async_session = async_sessionmaker(engine, expire_on_commit=False)
    
    # Use UTC for date comparison (go_live_date is stored in UTC)
    from datetime import timezone
    from datetime import datetime as dt
    import pytz
    
    today_utc = dt.now(timezone.utc).date()
    today_local = date.today()
    
    # Also show Pakistan time for reference
    BUSINESS_TIMEZONE = pytz.timezone('Asia/Karachi')  # UTC+5
    today_business = dt.now(BUSINESS_TIMEZONE).date()
    
    print(f"Cron job check - UTC date: {today_utc}, Local date: {today_local}, Pakistan date (PKT): {today_business}")
    
    async with async_session() as db:
        # Get all listings that went live today (based on UTC date)
        stmt = (
            select(ProductListing)
            .options(
                selectinload(ProductListing.store),
                selectinload(ProductListing.product)
            )
            .join(Store)
            .where(
                and_(
                    ProductListing.status == ListingStatusEnum.APPROVED,
                    ProductListing.go_live_date == today_utc,
                    Store.latitude.isnot(None),
                    Store.longitude.isnot(None)
                )
            )
        )
        
        result = await db.execute(stmt)
        listings = result.scalars().all()
        
        print(f"Found {len(listings)} listings that went live today (UTC date: {today_utc})")
        
        # Send notifications for each listing with timezone awareness
        for listing in listings:
            if listing.store:
                try:
                    await check_and_send_favorite_notifications_with_timezone(
                        db,
                        listing,
                        listing.store,
                        notification_hour=NOTIFICATION_HOUR,
                        notification_minute=NOTIFICATION_MINUTE
                    )
                except Exception as e:
                    print(f"Error sending notifications for listing {listing.listing_id}: {str(e)}")
        
        await db.commit()
    
    await engine.dispose()


if __name__ == "__main__":
    import asyncio
    asyncio.run(check_go_live_listings())

