import logging
from datetime import datetime, timedelta
from urllib.parse import parse_qs
from django.db.models import Q
from hotels.models import Reservation, Hotel
from .models import UserActivityLog, ViolationLog

# Настройка логирования
logging.basicConfig(level=logging.INFO)  # Устанавливаем уровень логирования
logger = logging.getLogger(__name__)  # Создаем логгер для текущего модуля

def check_reservations_and_generate_report():
    now = datetime.now()
    start_time = (now - timedelta(hours=12))
    end_time = now
    logger.info(f"Starting reservation check from {start_time} to {end_time}")

    # Получаем логи активности за период
    user_logs = UserActivityLog.objects.filter(created__range=(start_time, end_time))
    logger.info(f"Found {len(user_logs)} logs for analysis.")

    violations = []  # Список для записи нарушений

    for i, log in enumerate(user_logs, start=1):
        logger.debug(f"Processing log {i}: {log}")

        if not log.url_parameters:
            logger.warning(f"Log {i} skipped due to missing URL parameters.")
            continue  # Пропускаем записи без параметров URL

        # Парсим параметры URL
        params = parse_qs(log.url_parameters)
        external_id = params.get("utm_content", [None])[0]  # ID отеля
        room_number = params.get("utm_term", [None])[0]  # Номер комнаты

        logger.debug(f"Log {i} parsed parameters: external_id={external_id}, room_number={room_number}")

        if not external_id or not room_number:
            logger.warning(f"Log {i} skipped due to missing external_id or room_number.")
            continue  # Пропускаем, если данные не извлечены

        try:
            # Находим отель по external_id
            hotel = Hotel.objects.get(external_id=external_id)
            logger.debug(f"Log {i}: Found hotel {hotel.name} with external_id {external_id}.")
        except Hotel.DoesNotExist:
            logger.error(f"Log {i} skipped: No hotel found with external_id {external_id}.")
            continue

        # Ищем бронирование в Reservation
        matching_reservations = Reservation.objects.filter(
            hotel=hotel,
            room_number=room_number,
            check_in__lte=log.created,
            check_out__gte=log.created
        )
        logger.debug(f"Log {i}: Found {len(matching_reservations)} matching reservations.")

        if not matching_reservations.exists():
            # Если бронирование не найдено — записываем нарушение
            violation_details = (
                f"Log {i}: No reservation found for room {room_number} in hotel {external_id} at {log.created}."
            )
            violations.append(ViolationLog(
                hotel=hotel,
                room_number=room_number,
                violation_type="missed",
                violation_details=violation_details
            ))
            logger.warning(f"Log {i}: Violation recorded - {violation_details}")

    # Сохраняем все нарушения в базу
    if violations:
        ViolationLog.objects.bulk_create(violations)
        logger.info(f"Created {len(violations)} records in violation log.")
    else:
        logger.info("No violations found during this check.")

    logger.info("Reservation check completed.")
