
import logging
from datetime import datetime
from database import get_db_connection
from services.notification_service import onesignal_service

logger = logging.getLogger(__name__)

def send_daily_study_nudge():
    """
    Cron Job: Hourly
    Checks 'user_study_patterns' to see if current hour is a user's preferred study time.
    If so, sends a nudge.
    """
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    
    try:
        logger.info("Starting Daily Study Nudge...")
        
        # Current time details
        now = datetime.now()
        current_hour = now.hour
        # MySQL DAYOFWEEK: 1=Sunday, 7=Saturday
        current_day = now.isoweekday() % 7 + 1 
        
        # Find users who usually study at this hour on this day
        # Filter out users who have ALREADY studied today (don't annoy them)
        query = """
            SELECT DISTINCT p.user_id, u.fullname 
            FROM user_study_patterns p
            JOIN user u ON p.user_id = u.id
            LEFT JOIN user_analytics_summary s ON p.user_id = s.user_id
            WHERE p.day_of_week = %s 
            AND p.study_hour = %s
            AND p.total_time > 300 -- Only if they usually study > 5 mins
            AND (s.last_activity < DATE(NOW()) OR s.last_activity IS NULL) -- Has not studied today
        """
        
        cursor.execute(query, (current_day, current_hour))
        candidates = cursor.fetchall()
        
        sent_count = 0
        for user in candidates:
            # Personalize message
            name = user.get('fullname', 'Student')
            
            # Send via OneSignal
            # Note: In production, might want to batch this or use segments if possible,
            # but for personalized timing, individual targeting is best.
            onesignal_service.send_notification_to_users(
                user_ids=[user['user_id']],
                title=f"It's learning time, {name}! ⏰",
                message="This is your usual time to focus. Continue your progress now!",
                data={"type": "study_nudge"}
            )
            sent_count += 1
            
        logger.info(f"Daily Study Nudge sent to {sent_count} users.")
        return {"success": True, "sent_count": sent_count}
        
    except Exception as e:
        logger.error(f"Error in send_daily_study_nudge: {str(e)}")
        return {"success": False, "error": str(e)}
    finally:
        cursor.close()
        conn.close()

def send_inactivity_campaign():
    """
    Cron Job: Daily (e.g., 10 AM)
    Finds users inactive for 3 or 7 days and tries to bring them back.
    """
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    
    try:
        logger.info("Starting Re-engagement Campaign...")
        
        # 3-Day Inactivity Warning (Don't break streak!)
        query_3day = """
            SELECT user_id, current_streak FROM user_analytics_summary
            WHERE last_activity BETWEEN DATE_SUB(NOW(), INTERVAL 4 DAY) AND DATE_SUB(NOW(), INTERVAL 3 DAY)
            AND current_streak > 2
        """
        cursor.execute(query_3day)
        users_3day = cursor.fetchall()
        
        for user in users_3day:
            onesignal_service.send_notification_to_users(
                user_ids=[user['user_id']],
                title="Don't lose your streak! 🔥",
                message=f"You're on a {user['current_streak']}-day streak! logged in 3 days ago. Come back to save it.",
                data={"type": "inactivity_3day"}
            )

        # 7-Day Inactivity (We miss you)
        query_7day = """
            SELECT user_id FROM user_analytics_summary
            WHERE last_activity BETWEEN DATE_SUB(NOW(), INTERVAL 8 DAY) AND DATE_SUB(NOW(), INTERVAL 7 DAY)
        """
        cursor.execute(query_7day)
        users_7day = cursor.fetchall()
        
        for user in users_7day:
            onesignal_service.send_notification_to_users(
                user_ids=[user['user_id']],
                title="We miss you at Ashlya Academy! 👋",
                message="It's been a week. New contents are waiting for you.",
                data={"type": "inactivity_7day"}
            )
        
        total_sent = len(users_3day) + len(users_7day)
        logger.info(f"Re-engagement Campaign sent to {total_sent} users.")
        return {"success": True, "sent_3day": len(users_3day), "sent_7day": len(users_7day)}
        
    except Exception as e:
        logger.error(f"Error in send_inactivity_campaign: {str(e)}")
        return {"success": False, "error": str(e)}
    finally:
        cursor.close()
        conn.close()

def send_weekly_progress_report():
    """
    Cron Job: Weekly (Sunday Night)
    Sends summary of the week's achievements.
    """
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    
    try:
        logger.info("Starting Weekly Progress Report...")
        
        # Aggregate last 7 days activity
        # Note: This is an expensive query if many users. Should optimize in production.
        cursor.execute("""
            SELECT 
                u.id as user_id, 
                u.fullname as first_name,
                COUNT(DISTINCT rw.video_id) as videos_watched,
                COALESCE(SUM(rw.duration_watched), 0) / 60 as minutes_watched,
                COUNT(DISTINCT qs.id) as quizzes_taken
            FROM user u
            LEFT JOIN recently_watched rw ON u.id = rw.user_id 
                AND rw.time_watched > DATE_SUB(NOW(), INTERVAL 7 DAY)
            LEFT JOIN quiz_sessions qs ON u.id = qs.user_id 
                AND qs.created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
            WHERE u.is_verified = 1
            GROUP BY u.id
            HAVING minutes_watched > 10 OR quizzes_taken > 0
        """)
        
        active_users = cursor.fetchall()
        
        for user in active_users:
            msg = f"You watched {int(user['videos_watched'])} videos"
            if user['quizzes_taken'] > 0:
                msg += f" and took {user['quizzes_taken']} quizzes"
            msg += " this week! Keep it up! 🚀"
            
            onesignal_service.send_notification_to_users(
                user_ids=[user['user_id']],
                title="Your Weekly Progress Report 📊",
                message=msg,
                data={"type": "weekly_report"}
            )
            
        logger.info(f"Weekly Report sent to {len(active_users)} users.")
        return {"success": True, "sent_count": len(active_users)}
        
    except Exception as e:
        logger.error(f"Error in send_weekly_progress_report: {str(e)}")
        return {"success": False, "error": str(e)}
    finally:
        cursor.close()
        conn.close()
