"""
Alert Processing Scheduler.

Background job to periodically evaluate alert rules and create alerts.
Can be triggered via APScheduler, Celery, or manual endpoint.
"""

from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from src.core.database import DATABASE_URL, Base
from src.models.company import Company
from src.alerts.rule_engine import RuleEngine
from sqlalchemy import select
import logging
import asyncio

logger = logging.getLogger(__name__)

# Create engine for background tasks (shared with main app)
background_engine = create_async_engine(
    DATABASE_URL,
    echo=False,
    pool_size=5,
    pool_pre_ping=True,
)

BackgroundSessionLocal = sessionmaker(
    bind=background_engine,
    class_=AsyncSession,
    autocommit=False,
    autoflush=False,
)


async def process_all_company_alerts():
    """
    Process alert rules for all companies.
    Should be called every 5-15 minutes.
    """
    async with BackgroundSessionLocal() as session:
        try:
            # Get all active companies
            result = await session.execute(select(Company))
            companies = result.scalars().all()
            
            logger.info(f"Processing alerts for {len(companies)} companies")
            
            results = {}
            for company in companies:
                try:
                    engine = RuleEngine(session, company.id)
                    result = await engine.process_rules()
                    results[company.id] = result
                    logger.info(f"Company {company.id}: {result}")
                except Exception as e:
                    logger.error(f"Error processing alerts for company {company.id}: {e}")
                    results[company.id] = {'error': str(e)}
            
            return results
            
        except Exception as e:
            logger.error(f"Error in alert processing: {e}")
            return {'error': str(e)}


async def process_company_alerts(company_id: int):
    """Process alerts for a specific company"""
    async with BackgroundSessionLocal() as session:
        try:
            engine = RuleEngine(session, company_id)
            result = await engine.process_rules()
            logger.info(f"Company {company_id} alert processing: {result}")
            return result
        except Exception as e:
            logger.error(f"Error processing company {company_id}: {e}")
            return {'error': str(e)}


# ============================================================================
# APScheduler Integration (Optional)
# ============================================================================

try:
    from apscheduler.schedulers.asyncio import AsyncIOScheduler
    scheduler = AsyncIOScheduler()
    
    def schedule_alert_processing():
        """Schedule alert processing to run every 10 minutes"""
        scheduler.add_job(
            process_all_company_alerts,
            'interval',
            minutes=10,
            id='process_alerts',
            name='Process all company alerts',
            replace_existing=True
        )
        logger.info("Alert processing scheduled")
    
    def start_scheduler():
        """Start the scheduler"""
        if not scheduler.running:
            scheduler.start()
            logger.info("Scheduler started")
    
    def stop_scheduler():
        """Stop the scheduler"""
        if scheduler.running:
            scheduler.shutdown()
            logger.info("Scheduler stopped")

except ImportError:
    logger.warning("APScheduler not installed. Background alert processing disabled.")
    scheduler = None


# ============================================================================
# Manual Test
# ============================================================================

async def main():
    """Test alert processing"""
    print("Testing alert processing...")
    result = await process_all_company_alerts()
    print(f"Result: {result}")


if __name__ == "__main__":
    asyncio.run(main())
