"""Notification integration helpers for RateRight Australian Construction Marketplace"""
import logging
from typing import Optional, Dict, Any

from ..services.notification_service import notification_service
from ..models.notification import NotificationType

logger = logging.getLogger(__name__)


class NotificationTriggers:
    """Helper class for triggering notifications from various parts of the application"""
    
    @staticmethod
    def job_match_found(user_id: int, job_title: str, job_id: int, match_score: Optional[float] = None):
        """Trigger notification when a job matches user criteria"""
        try:
            content = f"A new job '{job_title}' matches your skills and preferences."
            if match_score:
                content += f" Match score: {match_score:.1%}"
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.JOB_MATCH,
                title="New Job Match Found!",
                content=content,
                priority=3,  # Medium priority
                category="job_alerts",
                action_url=f"/jobs/{job_id}",
                template_context={
                    'job_title': job_title,
                    'job_id': job_id,
                    'match_score': match_score
                }
            )
            logger.info(f"Job match notification sent to user {user_id} for job {job_id}")
            
        except Exception as e:
            logger.error(f"Failed to send job match notification: {e}")
    
    @staticmethod
    def application_status_update(user_id: int, job_title: str, status: str, job_id: int):
        """Trigger notification when job application status changes"""
        try:
            status_messages = {
                'accepted': f"Great news! Your application for '{job_title}' has been accepted.",
                'rejected': f"Your application for '{job_title}' was not successful this time.",
                'under_review': f"Your application for '{job_title}' is currently under review.",
                'shortlisted': f"Congratulations! You've been shortlisted for '{job_title}'."
            }
            
            content = status_messages.get(status, f"Your application status for '{job_title}' has been updated to: {status}")
            priority = 2 if status in ['accepted', 'shortlisted'] else 3
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.JOB_APPLICATION_UPDATE,
                title="Application Status Update",
                content=content,
                priority=priority,
                category="job_alerts",
                action_url=f"/applications/{job_id}",
                template_context={
                    'job_title': job_title,
                    'status': status,
                    'job_id': job_id
                }
            )
            logger.info(f"Application status notification sent to user {user_id}: {status}")
            
        except Exception as e:
            logger.error(f"Failed to send application status notification: {e}")
    
    @staticmethod
    def contract_awarded(user_id: int, job_title: str, contract_value: float, job_id: int):
        """Trigger notification when contract is awarded to user"""
        try:
            content = f"Congratulations! You've been awarded the contract for '{job_title}'. Contract value: ${contract_value:,.2f}"
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.CONTRACT_AWARDED,
                title="Contract Awarded! 🎉",
                content=content,
                priority=1,  # Urgent - great news!
                category="job_alerts",
                action_url=f"/contracts/{job_id}",
                template_context={
                    'job_title': job_title,
                    'contract_value': contract_value,
                    'job_id': job_id
                }
            )
            logger.info(f"Contract awarded notification sent to user {user_id}")
            
        except Exception as e:
            logger.error(f"Failed to send contract awarded notification: {e}")
    
    @staticmethod
    def payment_received(user_id: int, amount: float, job_title: str, payment_id: int):
        """Trigger notification when payment is received"""
        try:
            content = f"Payment of ${amount:,.2f} has been received for '{job_title}'"
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.PAYMENT_RECEIVED,
                title="Payment Received! 💰",
                content=content,
                priority=2,  # High priority
                category="financial",
                action_url=f"/payments/{payment_id}",
                template_context={
                    'amount': amount,
                    'job_title': job_title,
                    'payment_id': payment_id
                }
            )
            logger.info(f"Payment received notification sent to user {user_id}: ${amount}")
            
        except Exception as e:
            logger.error(f"Failed to send payment received notification: {e}")
    
    @staticmethod
    def payment_due_reminder(user_id: int, amount: float, due_date: str, job_title: str):
        """Trigger notification for upcoming payment due"""
        try:
            content = f"Payment of ${amount:,.2f} for '{job_title}' is due on {due_date}"
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.PAYMENT_DUE,
                title="Payment Due Reminder",
                content=content,
                priority=2,  # High priority
                category="financial",
                action_url="/payments/pending",
                template_context={
                    'amount': amount,
                    'due_date': due_date,
                    'job_title': job_title
                }
            )
            logger.info(f"Payment due reminder sent to user {user_id}")
            
        except Exception as e:
            logger.error(f"Failed to send payment due notification: {e}")
    
    @staticmethod
    def rating_received(user_id: int, rating: float, reviewer_name: str, job_title: str, review_id: int):
        """Trigger notification when user receives a rating"""
        try:
            stars = "⭐" * int(rating)
            content = f"{reviewer_name} rated your work on '{job_title}': {stars} ({rating}/5)"
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.RATING_RECEIVED,
                title="New Rating Received!",
                content=content,
                priority=3,  # Medium priority
                category="social",
                action_url=f"/reviews/{review_id}",
                template_context={
                    'rating': rating,
                    'reviewer_name': reviewer_name,
                    'job_title': job_title,
                    'review_id': review_id,
                    'stars': stars
                }
            )
            logger.info(f"Rating received notification sent to user {user_id}: {rating} stars")
            
        except Exception as e:
            logger.error(f"Failed to send rating received notification: {e}")
    
    @staticmethod
    def achievement_unlocked(user_id: int, achievement_name: str, achievement_description: str, points_earned: int):
        """Trigger notification when user unlocks an achievement"""
        try:
            content = f"🏆 Achievement Unlocked: {achievement_name}! {achievement_description} (+{points_earned} points)"
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.ACHIEVEMENT_UNLOCKED,
                title="Achievement Unlocked! 🏆",
                content=content,
                priority=4,  # Lower priority for gamification
                category="social",
                action_url="/profile/achievements",
                template_context={
                    'achievement_name': achievement_name,
                    'achievement_description': achievement_description,
                    'points_earned': points_earned
                }
            )
            logger.info(f"Achievement notification sent to user {user_id}: {achievement_name}")
            
        except Exception as e:
            logger.error(f"Failed to send achievement notification: {e}")
    
    @staticmethod
    def message_received(user_id: int, sender_name: str, message_preview: str, conversation_id: int, sender_id: int = None, message_id: int = None):
        """Trigger notification when user receives a new message"""
        try:
            content = f"New message from {sender_name}: {message_preview[:50]}..."
            
            # Generate proper action URL:
            # If message_id is provided, use the individual message route
            # Otherwise, use conversation view with sender_id
            if message_id:
                action_url = f"/messages/{message_id}"
            elif sender_id:
                action_url = f"/messages/view?user_id={sender_id}"
            else:
                # Fallback to general messages interface
                action_url = "/messages"
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.MESSAGE_RECEIVED,
                title="New Message",
                content=content,
                priority=3,  # Medium priority
                category="social",
                action_url=action_url,
                template_context={
                    'sender_name': sender_name,
                    'message_preview': message_preview,
                    'conversation_id': conversation_id,
                    'sender_id': sender_id,
                    'message_id': message_id
                }
            )
            logger.info(f"Message notification sent to user {user_id} from {sender_name}")
            
        except Exception as e:
            logger.error(f"Failed to send message notification: {e}")
    
    @staticmethod
    def insurance_expiry_warning(user_id: int, insurance_type: str, expiry_date: str, days_until_expiry: int):
        """Trigger notification for upcoming insurance expiry"""
        try:
            content = f"Your {insurance_type} expires on {expiry_date} ({days_until_expiry} days). Please renew to maintain compliance."
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.INSURANCE_EXPIRY,
                title="Insurance Expiry Warning ⚠️",
                content=content,
                priority=1 if days_until_expiry <= 7 else 2,  # Urgent if less than 7 days
                category="compliance",
                action_url="/profile/insurance",
                template_context={
                    'insurance_type': insurance_type,
                    'expiry_date': expiry_date,
                    'days_until_expiry': days_until_expiry
                }
            )
            logger.info(f"Insurance expiry warning sent to user {user_id}: {insurance_type}")
            
        except Exception as e:
            logger.error(f"Failed to send insurance expiry notification: {e}")
    
    @staticmethod
    def certification_renewal_reminder(user_id: int, certification_name: str, renewal_date: str, days_until_renewal: int):
        """Trigger notification for upcoming certification renewal"""
        try:
            content = f"Your {certification_name} needs renewal by {renewal_date} ({days_until_renewal} days). Keep your qualifications current."
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.CERTIFICATION_RENEWAL,
                title="Certification Renewal Reminder",
                content=content,
                priority=2,  # High priority for compliance
                category="compliance",
                action_url="/profile/certifications",
                template_context={
                    'certification_name': certification_name,
                    'renewal_date': renewal_date,
                    'days_until_renewal': days_until_renewal
                }
            )
            logger.info(f"Certification renewal reminder sent to user {user_id}: {certification_name}")
            
        except Exception as e:
            logger.error(f"Failed to send certification renewal notification: {e}")
    
    @staticmethod
    def system_announcement(user_ids: list, title: str, content: str, action_url: Optional[str] = None, urgent: bool = False):
        """Send system announcement to multiple users"""
        try:
            priority = 1 if urgent else 3
            
            for user_id in user_ids:
                notification_service.send_notification(
                    user_id=user_id,
                    notification_type=NotificationType.SYSTEM_ANNOUNCEMENT,
                    title=title,
                    content=content,
                    priority=priority,
                    category="system",
                    action_url=action_url,
                    force_send=urgent  # Override quiet hours if urgent
                )
            
            logger.info(f"System announcement sent to {len(user_ids)} users: {title}")
            
        except Exception as e:
            logger.error(f"Failed to send system announcement: {e}")
    
    @staticmethod
    def security_alert(user_id: int, alert_type: str, ip_address: Optional[str] = None, device_info: Optional[str] = None):
        """Trigger security alert notification"""
        try:
            alert_messages = {
                'login_from_new_device': f"New login detected from {device_info or 'unknown device'}" + (f" at IP {ip_address}" if ip_address else ""),
                'password_changed': "Your password was recently changed. If this wasn't you, please contact support immediately.",
                'suspicious_activity': "Suspicious activity detected on your account. Please review your recent activity.",
                'account_locked': "Your account has been temporarily locked due to multiple failed login attempts."
            }
            
            content = alert_messages.get(alert_type, f"Security alert: {alert_type}")
            
            notification_service.send_notification(
                user_id=user_id,
                notification_type=NotificationType.SECURITY_ALERT,
                title="Security Alert 🔒",
                content=content,
                priority=1,  # Always urgent
                category="system",
                action_url="/profile/security",
                force_send=True,  # Always send regardless of preferences
                template_context={
                    'alert_type': alert_type,
                    'ip_address': ip_address,
                    'device_info': device_info
                }
            )
            logger.info(f"Security alert sent to user {user_id}: {alert_type}")
            
        except Exception as e:
            logger.error(f"Failed to send security alert: {e}")


# Convenience functions for easy integration
def notify_job_match(user_id: int, job_title: str, job_id: int, match_score: Optional[float] = None):
    """Convenience function for job match notifications"""
    NotificationTriggers.job_match_found(user_id, job_title, job_id, match_score)

def notify_payment_received(user_id: int, amount: float, job_title: str, payment_id: int):
    """Convenience function for payment received notifications"""
    NotificationTriggers.payment_received(user_id, amount, job_title, payment_id)

def notify_achievement_unlocked(user_id: int, achievement_name: str, achievement_description: str, points_earned: int):
    """Convenience function for achievement notifications"""
    NotificationTriggers.achievement_unlocked(user_id, achievement_name, achievement_description, points_earned)

def notify_rating_received(user_id: int, rating: float, reviewer_name: str, job_title: str, review_id: int):
    """Convenience function for rating notifications"""
    NotificationTriggers.rating_received(user_id, rating, reviewer_name, job_title, review_id)

def notify_security_alert(user_id: int, alert_type: str, **kwargs):
    """Convenience function for security alerts"""
    NotificationTriggers.security_alert(user_id, alert_type, **kwargs)
