from apscheduler.schedulers.background import BackgroundScheduler
import logging
from datetime import datetime
from app import mysql
from celery import shared_task
from app.utils.celery_app import celery

logger = logging.getLogger(__name__)

def refresh_all_tokens():
    try:
        cursor = mysql.connection.cursor()
        
        # Get companies with tokens older than 50 days
        cursor.execute("""
            SELECT id 
            FROM companies 
            WHERE whatsapp_token_updated_at < NOW() - INTERVAL 50 DAY
            AND whatsapp_access_token IS NOT NULL
        """)
        
        for (company_id,) in cursor.fetchall():
            try:
                # Import here to avoid circular import
                from app.routes.whatsapp import refresh_whatsapp_token
                new_token = refresh_whatsapp_token(company_id)
                if new_token:
                    logger.info(f"Successfully refreshed token for company {company_id}")
                else:
                    logger.error(f"Failed to refresh token for company {company_id}")
            except Exception as e:
                logger.error(f"Error refreshing token for company {company_id}: {str(e)}")
                
    except Exception as e:
        logger.error(f"Error in refresh_all_tokens: {str(e)}")

def create_scheduler(app):
    """Create and start the scheduler with the Flask app context"""
    try:
        scheduler = BackgroundScheduler()
        
        # Add the job with app context
        @scheduler.scheduled_job('cron', hour=0)
        def scheduled_refresh():
            with app.app_context():
                refresh_all_tokens()
        
        scheduler.start()
        logger.info("Scheduler started successfully")
        return scheduler
    except Exception as e:
        logger.error(f"Error initializing scheduler: {str(e)}")
        return None

@celery.task(name='app.tasks.process_campaign')
def process_campaign(campaign_id):
    logger.info(f"Processing campaign: {campaign_id}")
    from app.utils.call_campaign import process_campaign as process_campaign_func
    return process_campaign_func(campaign_id)

@celery.task(name='app.tasks.test_connection')
def test_connection():
    logger.info("Test task executed successfully")
    return "Connection successful!"
