"""
Background cron jobs for analytics and performance score calculations.
"""
import logging
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from datetime import datetime

logger = logging.getLogger(__name__)

# Global scheduler instance
scheduler = BackgroundScheduler()

def start_analytics_cron():
    """Start the analytics cron jobs."""
    try:
        # Monthly performance score calculation - runs on the 1st of each month at 2 AM
        scheduler.add_job(
            func=calculate_monthly_performance_scores_job,
            trigger=CronTrigger(day=1, hour=2, minute=0),
            id='monthly_performance_scores',
            name='Monthly Performance Score Calculation',
            replace_existing=True
        )
        
        # Daily Twitter metrics update - runs daily at 1 AM
        scheduler.add_job(
            func=daily_twitter_metrics_job,
            trigger=CronTrigger(hour=1, minute=0),
            id='daily_twitter_metrics',
            name='Daily Twitter Metrics Update',
            replace_existing=True
        )
        
        scheduler.start()
        logger.info("Analytics cron jobs started successfully")
        
    except Exception as e:
        logger.error(f"Error starting analytics cron jobs: {str(e)}")

def stop_analytics_cron():
    """Stop the analytics cron jobs."""
    try:
        scheduler.shutdown()
        logger.info("Analytics cron jobs stopped")
    except Exception as e:
        logger.error(f"Error stopping analytics cron jobs: {str(e)}")

def calculate_monthly_performance_scores_job():
    """Monthly cron job to calculate performance scores for all stores."""
    try:
        logger.info("Starting monthly performance score calculation job")
        
        from src.marketing.apps.Analytics.twitter_analytics import calculate_monthly_performance_scores
        
        result = calculate_monthly_performance_scores()
        
        if result["success"]:
            logger.info(f"Monthly performance score calculation completed: {result['message']}")
        else:
            logger.error(f"Monthly performance score calculation failed: {result['message']}")
            
    except Exception as e:
        logger.error(f"Error in monthly performance score calculation job: {str(e)}")

def daily_twitter_metrics_job():
    """Daily cron job to update Twitter metrics."""
    try:
        logger.info("Starting daily Twitter metrics update job")
        
        from src.marketing.apps.Analytics.twitter_analytics import update_twitter_metrics_daily
        
        update_twitter_metrics_daily()
        
        logger.info("Daily Twitter metrics update job completed")
        
    except Exception as e:
        logger.error(f"Error in daily Twitter metrics update job: {str(e)}")

def get_cron_status():
    """Get the status of all cron jobs."""
    try:
        jobs = []
        for job in scheduler.get_jobs():
            jobs.append({
                "id": job.id,
                "name": job.name,
                "next_run_time": job.next_run_time.isoformat() if job.next_run_time else None,
                "trigger": str(job.trigger)
            })
        
        return {
            "scheduler_running": scheduler.running,
            "jobs": jobs
        }
    except Exception as e:
        logger.error(f"Error getting cron status: {str(e)}")
        return {"error": str(e)}

def trigger_manual_calculation(store_id: int, branch_id: int = None):
    """Manually trigger performance score calculation for a specific store."""
    try:
        logger.info(f"Manually triggering performance score calculation for store {store_id}")
        
        from src.marketing.apps.Analytics.twitter_analytics import calculate_store_performance_score
        from src.utils.db import get_db_session
        
        db = get_db_session()
        result = calculate_store_performance_score(db, store_id, branch_id)
        db.close()
        
        if result["success"]:
            logger.info(f"Manual calculation completed for store {store_id}: Score {result['overall_score']}")
        else:
            logger.error(f"Manual calculation failed for store {store_id}: {result['message']}")
            
        return result
        
    except Exception as e:
        logger.error(f"Error in manual performance score calculation: {str(e)}")
        return {"success": False, "message": str(e)}
