"""
Automated Security Scan Task
This module can be integrated with task schedulers like Celery or APScheduler
to run security scans automatically at scheduled intervals.
"""

from datetime import datetime
import logging
from ...security.services.security_scan_service import security_scan_service
from ...shared.config.database import get_db
from ...shared.config.logging_config import get_logger

logger = get_logger(__name__)

def run_scheduled_security_scan():
    """
    Task function to run scheduled security scans.
    This can be called by:
    - Celery periodic tasks
    - APScheduler
    - Cron jobs
    - Systemd timers
    """
    try:
        logger.info("Starting scheduled security scan")
        db_gen = get_db()
        db = next(db_gen)
        
        try:
            results = security_scan_service.run_full_scan(db=db)
            logger.info(
                f"Security scan completed: {results['total_issues']} issues found "
                f"({results['critical_issues']} critical, {results['high_issues']} high)"
            )
            return results
        finally:
            db.close()
    except Exception as e:
        logger.error(f"Error running scheduled security scan: {str(e)}", exc_info=True)
        raise

# Example Celery task (uncomment if using Celery):
# from celery import shared_task
# 
# @shared_task
# def scheduled_security_scan_task():
#     """Celery task for scheduled security scans"""
#     return run_scheduled_security_scan()

# Example APScheduler job (uncomment if using APScheduler):
# from apscheduler.schedulers.background import BackgroundScheduler
# 
# def setup_scheduled_scans():
#     """Setup scheduled security scans using APScheduler"""
#     scheduler = BackgroundScheduler()
#     scheduler.add_job(
#         run_scheduled_security_scan,
#         'interval',
#         hours=24,  # Run every 24 hours
#         id='security_scan',
#         name='Automated Security Scan',
#         replace_existing=True
#     )
#     scheduler.start()
#     return scheduler

