import logging
from django.conf import settings
from django.utils import timezone
from .models import UserFCMToken, UserPattern
from datetime import datetime, time, timedelta

logger = logging.getLogger(__name__)

class PushNotificationService:
    def __init__(self):
        self.firebase_initialized = False
        self.initialize_firebase()
    
    def initialize_firebase(self):
        """Initialize Firebase Admin SDK"""
        try:
            import firebase_admin
            from firebase_admin import credentials, messaging
            
            if not firebase_admin._apps:
                # Try to use service account key if available
                try:
                    cred = credentials.Certificate(settings.FIREBASE_SERVICE_ACCOUNT_KEY)
                    firebase_admin.initialize_app(cred)
                    self.firebase_initialized = True
                    logger.info("Firebase initialized with service account key")
                except Exception as e:
                    logger.warning(f"Could not initialize Firebase with service account: {e}")
                    # Fallback to default credentials with project ID
                    try:
                        project_id = getattr(settings, 'FIREBASE_PROJECT_ID', None)
                        if project_id:
                            firebase_admin.initialize_app(options={'projectId': project_id})
                            self.firebase_initialized = True
                            logger.info(f"Firebase initialized with project ID: {project_id}")
                        else:
                            firebase_admin.initialize_app()
                            self.firebase_initialized = True
                            logger.info("Firebase initialized with default credentials")
                    except Exception as e2:
                        logger.error(f"Could not initialize Firebase: {e2}")
                        self.firebase_initialized = False
            else:
                self.firebase_initialized = True
                logger.info("Firebase already initialized")
                
        except ImportError:
            logger.error("Firebase Admin SDK not installed. Run: pip install firebase-admin")
            self.firebase_initialized = False
    
    def send_notification(self, user_id: str, title: str, body: str, data: dict = None):
        """Send push notification to user"""
        if not self.firebase_initialized:
            logger.error("Firebase not initialized, cannot send notification")
            return False
            
        try:
            from firebase_admin import messaging
            
            # Get user's FCM token
            fcm_token = UserFCMToken.objects.filter(
                user_id=user_id,
                is_active=True
            ).first()
            
            if not fcm_token:
                logger.warning(f"No FCM token found for user {user_id}")
                return False
            
            # Create message
            message = messaging.Message(
                notification=messaging.Notification(
                    title=title,
                    body=body
                ),
                data=data or {},
                token=fcm_token.fcm_token
            )
            
            # Send message
            response = messaging.send(message)
            logger.info(f"Successfully sent message: {response}")
            return True
            
        except Exception as e:
            logger.error(f"Error sending push notification: {e}")
            return False
    
    def send_smart_reminder(self, user_id: str, question_type: str, typical_time: str):
        """Send smart reminder notification"""
        messages = {
            'clock_in': {
                'title': '⏰ Time to Start Your Day',
                'body': f"You usually clock in at {typical_time}"
            },
            'lunch_out': {
                'title': '🍽️ Lunch Time',
                'body': f"You typically go to lunch at {typical_time}"
            },
            'lunch_in': {
                'title': '⏰ Lunch Break Ending',
                'body': f"You usually return from lunch at {typical_time}"
            },
            'clock_out': {
                'title': '🏠 End of Day',
                'body': f"You usually clock out at {typical_time}"
            }
        }
        
        message_data = messages.get(question_type, {
            'title': 'Flexwise Reminder',
            'body': 'You have a reminder'
        })
        
        return self.send_notification(
            user_id=user_id,
            title=message_data['title'],
            body=message_data['body'],
            data={
                'question_type': question_type,
                'typical_time': typical_time,
                'action': question_type
            }
        )
    
    def user_already_did_action(self, user_id: str, question_type: str) -> bool:
        """Check if user already did this action today"""
        from stamps.models import Stamp
        today = timezone.now().date()
        
        return Stamp.objects.filter(
            user__id=user_id,
            stamp_function=question_type,
            date=today
        ).exists()
    
    def time_to_seconds(self, t: time) -> int:
        """Convert time to seconds since midnight"""
        return t.hour * 3600 + t.minute * 60 + t.second
    
    def seconds_to_time(self, seconds: int) -> time:
        """Convert seconds since midnight to time"""
        hours = seconds // 3600
        minutes = (seconds % 3600) // 60
        secs = seconds % 60
        return time(hours, minutes, secs)
    
    def subtract_minutes(self, time_obj: time, minutes: int) -> time:
        """Subtract minutes from time object"""
        total_seconds = self.time_to_seconds(time_obj) - (minutes * 60)
        if total_seconds < 0:
            total_seconds += 24 * 3600  # Wrap to previous day
        return self.seconds_to_time(total_seconds)
    
    def get_next_occurrence(self, time_obj: time) -> datetime:
        """Get next occurrence of time as datetime"""
        today = timezone.now().date()
        target_datetime = datetime.combine(today, time_obj)
        
        # If time has passed today, schedule for tomorrow
        if target_datetime <= timezone.now():
            target_datetime += timedelta(days=1)
        
        return target_datetime
