
from flask import Blueprint, request, jsonify
from functools import wraps
from config.config_settings import CRON_SECRET
from cron_handlers.analytics_jobs import (
    update_user_analytics_summary, 
    analyze_study_patterns,
    update_topic_analytics,
    generate_learning_insights
)
from cron_handlers.notification_jobs import (
    send_daily_study_nudge, 
    send_inactivity_campaign, 
    send_weekly_progress_report
)
import logging

logger = logging.getLogger(__name__)
cron_bp = Blueprint('cron', __name__)

def require_cron_secret(f):
    """Decorator to protect cron endpoints"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # Check header first, then query param as fallback
        secret = request.headers.get('X-Cron-Secret') or request.args.get('secret')
        
        if not secret or secret != CRON_SECRET:
            logger.warning(f"Unauthorized cron access attempt from {request.remote_addr}")
            return jsonify({"error": "Unauthorized", "message": "Invalid Cron Secret"}), 401
        return f(*args, **kwargs)
    return decorated_function

# ==========================================
# Analytics Jobs (Data Population)
# ==========================================

@cron_bp.route('/api/cron/analytics/daily', methods=['GET'])
@require_cron_secret
def run_daily_analytics():
    """Run nightly user stats calculation (streaks, totals)"""
    result = update_user_analytics_summary()
    status = 200 if result.get('success') else 500
    return jsonify(result), status

@cron_bp.route('/api/cron/analytics/study-patterns', methods=['GET'])
@require_cron_secret
def run_study_pattern_analysis():
    """Run weekly/daily analysis of study times"""
    result = analyze_study_patterns()
    status = 200 if result.get('success') else 500
    return jsonify(result), status

@cron_bp.route('/api/cron/analytics/topics', methods=['GET'])
@require_cron_secret
def run_topic_analytics():
    """Run aggregations for topic performance"""
    result = update_topic_analytics()
    status = 200 if result.get('success') else 500
    return jsonify(result), status

@cron_bp.route('/api/cron/analytics/insights', methods=['GET'])
@require_cron_secret
def run_insight_generation():
    """Run AI insight generation based on topics"""
    result = generate_learning_insights()
    status = 200 if result.get('success') else 500
    return jsonify(result), status

# ==========================================
# Notification Jobs (Campaigns)
# ==========================================

@cron_bp.route('/api/cron/notifications/nudge-hourly', methods=['GET'])
@require_cron_secret
def run_hourly_nudge():
    """Run hourly check for study time preferences"""
    result = send_daily_study_nudge()
    status = 200 if result.get('success') else 500
    return jsonify(result), status

@cron_bp.route('/api/cron/notifications/mock-tests', methods=['GET'])
@require_cron_secret
def run_mock_test_updates():
    """Run check for new mock test results"""
    # Import locally to avoid circular imports if any
    from cron_handlers.notification_jobs import send_mock_test_updates
    result = send_mock_test_updates()
    status = 200 if result.get('success') else 500
    return jsonify(result), status

@cron_bp.route('/api/cron/notifications/inactivity-daily', methods=['GET'])
@require_cron_secret
def run_daily_inactivity_check():
    """Run daily check for inactive users (re-engagement)"""
    result = send_inactivity_campaign()
    status = 200 if result.get('success') else 500
    return jsonify(result), status

@cron_bp.route('/api/cron/notifications/weekly-report', methods=['GET'])
@require_cron_secret
def run_weekly_report():
    """Run weekly progress report (Sunday night)"""
    result = send_weekly_progress_report()
    status = 200 if result.get('success') else 500
    return jsonify(result), status
