import os
import logging
from logging.handlers import RotatingFileHandler, SMTPHandler
from pathlib import Path

def configure_logging(app):
    """Configure logging for the application."""
    # Create logs directory if it doesn't exist
    log_dir = Path('logs')
    log_dir.mkdir(exist_ok=True)
    
    # Set up basic logging configuration
    logging.basicConfig(
        level=app.config['LOG_LEVEL'],
        format=app.config['LOG_FORMAT'],
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    # Configure application logger
    app.logger.setLevel(app.config['LOG_LEVEL'])
    
    # Remove default handlers
    for handler in app.logger.handlers[:]:
        app.logger.removeHandler(handler)
    
    # Add file handler for application logs
    file_handler = RotatingFileHandler(
        'logs/mold_cost_calculator.log',
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=10,
        encoding='utf-8'
    )
    file_handler.setFormatter(logging.Formatter(app.config['LOG_FORMAT']))
    file_handler.setLevel(app.config['LOG_LEVEL'])
    app.logger.addHandler(file_handler)
    
    # Add file handler for error logs
    error_handler = RotatingFileHandler(
        'logs/error.log',
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=10,
        encoding='utf-8'
    )
    error_handler.setFormatter(logging.Formatter(app.config['LOG_FORMAT']))
    error_handler.setLevel(logging.ERROR)
    app.logger.addHandler(error_handler)
    
    # Add file handler for access logs
    access_handler = RotatingFileHandler(
        'logs/access.log',
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=10,
        encoding='utf-8'
    )
    access_handler.setFormatter(logging.Formatter(app.config['LOG_FORMAT']))
    access_handler.setLevel(logging.INFO)
    app.logger.addHandler(access_handler)
    
    # Add console handler if LOG_TO_STDOUT is set
    if app.config.get('LOG_TO_STDOUT'):
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(logging.Formatter(app.config['LOG_FORMAT']))
        console_handler.setLevel(app.config['LOG_LEVEL'])
        app.logger.addHandler(console_handler)
    
    # Add email handler for critical errors in production
    if not app.debug and not app.testing and app.config.get('MAIL_SERVER'):
        mail_handler = SMTPHandler(
            mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
            fromaddr=app.config['MAIL_DEFAULT_SENDER'],
            toaddrs=[app.config['ADMIN_EMAIL']],
            subject='Mold Cost Calculator Error'
        )
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(logging.Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s
            Message:
            %(message)s
        '''))
        app.logger.addHandler(mail_handler)
    
    # Configure SQLAlchemy logging
    if app.config.get('SQLALCHEMY_ECHO'):
        logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
    
    # Configure Werkzeug logging
    logging.getLogger('werkzeug').setLevel(logging.INFO)
    
    # Log startup message
    app.logger.info('Mold Cost Calculator startup')
    
    return app.logger 