import asyncio
import logging
from datetime import datetime, timezone, timedelta
from typing import List

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from src.core.db import SessionLocal
from src.core.config import settings
from src.services.campflow import campflow_client
from src.services.api_service import fetch_event_tn_data
from src.services.mail_service import mail_service
from src.services.mail_stats_service import generate_email_stats
from src.events.models import NotificationHistory
from src.services.campflow import get_campflow_client
from src.services.logging_service import log_action
from src.services.pdf_service import make_filename_safe

logger = logging.getLogger(__name__)

async def check_and_send_notifications():
    """
    Main loop to check for upcoming events and send automated stats emails.
    Runs indefinitely with a sleep interval.
    """
    while True:
        try:
            logger.info("Starting background notification check...")
            await check_and_send_all_groups()
        except Exception as e:
            logger.error(f"Error in notification check loop: {e}")

        # Sleep for 1 hour before next check
        await asyncio.sleep(3600)


async def check_and_send_all_groups(session_override: AsyncSession | None = None):
    """
    Check and send notifications for all groups in the database.
    If session_override is provided, uses that session instead of creating a new one.
    """
    if session_override:
        await _check_and_send_all_groups_internal(session_override)
    else:
        async with SessionLocal() as session:
            await _check_and_send_all_groups_internal(session)


async def _check_and_send_all_groups_internal(session: AsyncSession):
    from src.group_settings.repo import GroupConfigRepo
    group_repo = GroupConfigRepo(session)
    all_groups = await group_repo.get_all()

    for group in all_groups:
        if not group.auto_mail_recipient:
            # Skip groups that haven't opted into automated mails
            continue

        logger.info(f"Checking events for group: {group.group_email}")
        
        # Create a per-group client
        client = get_campflow_client(group)
        
        try:
            events = await client.get_events(force_refresh=True)
            now = datetime.now(timezone.utc)

            for event in events:
                list_id = event.get("list_id")
                if not list_id:
                    continue

                # Check if already sent (globally for this event ID)
                stmt = select(NotificationHistory).where(NotificationHistory.list_id == list_id)
                result = await session.execute(stmt)
                if result.scalar_one_or_none():
                    continue

                start_date_str = event.get("start_date")
                published = event.get("published", False)
                if not start_date_str:
                    continue

                # Convert to UTC datetime
                start_date = datetime.fromisoformat(start_date_str.replace("Z", "+00:00"))
                if start_date.tzinfo is None:
                    start_date = start_date.replace(tzinfo=timezone.utc)
                
                delta = start_date - now
                
                condition_met = False
                if timedelta(days=0) < delta < timedelta(days=7):
                    condition_met = True
                elif timedelta(days=0) < delta < timedelta(days=14) and not published:
                    condition_met = True

                if condition_met:
                    logger.info(f"Conditions met for event {list_id} (Group: {group.group_email}).")
                    
                    # Fetch event info for the title and URL
                    event_info = await client.get_event_details(list_id)
                    if not event_info:
                        continue

                    # Fetch participant data for stats
                    tn_data, gf_data, _ = await fetch_event_tn_data(list_id, group_config=group)
                    
                    # Generate Email Content
                    html_body, inline_images = generate_email_stats(tn_data, gf_data, event_info)
                    
                    # Send Email
                    success = await mail_service.send_auto_mail(
                        to_address=group.auto_mail_recipient,
                        event_title=event_info.get("title", "Event"),
                        html_content=html_body,
                        inline_images=inline_images,
                        group_config=group
                    )

                    if success:
                        # Audit Log
                        await log_action(
                            session=session,
                            group_email=group.group_email,
                            user_email="SYSTEM_AUTOMATION",
                            action="SEND_MAIL",
                            details=f"Automated stats email sent for event: {event_info.get('title')} to {group.auto_mail_recipient}"
                        )

                        history = NotificationHistory(list_id=list_id)
                        session.add(history)
                        await session.commit()
                        logger.info(f"Notification recorded for event {list_id}")

        except Exception as e:
            logger.error(f"Error processing group {group.group_email}: {e}")


async def send_test_email(session: SessionLocal, group_config: "GroupConfig", override_recipient: str | None = None):
    """Send a test email to the configured recipient (or override) for the group."""
    recipient = override_recipient or group_config.auto_mail_recipient

    if not recipient:
        logger.warning(f"No recipient set for group {group_config.group_email}. Skipping test email.")
        return

    logger.info(f"Sending test email for group {group_config.group_email} to {recipient}")

    success = await mail_service.send_auto_mail(
        to_address=recipient,
        event_title="TEST EMAIL - CampflowToolbox",
        html_content="""
        <div style="font-family: sans-serif; color: #333; padding: 20px;">
            <h1 style="color: #3b82f6;">✓ Email Setup Working!</h1>
            <p>Hello,</p>
            <p>This is a test email from your <strong>CampflowToolbox</strong> instance.</p>
            <p>Your SMTP settings for the group <strong>""" + group_config.group_email + """</strong> have been successfully verified.</p>
            <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
            <p style="font-size: 0.8rem; color: #888;">This is an automated message. You don't need to reply.</p>
        </div>
        """,
        group_config=group_config
    )

    if success:
        await log_action(
            session=session,
            group_email=group_config.group_email,
            user_email=override_recipient or "SYSTEM",
            action="SEND_MAIL",
            details=f"Test email sent to {recipient}"
        )
