"""
Notification System for Task Manager MCP

Provides a simple notification and reminder system that can be extended
with real notification backends (email, Slack, etc.)
"""

import json
import os
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, asdict


@dataclass
class Notification:
    """Represents a notification"""
    id: str
    recipient_id: str
    message: str
    notification_type: str
    priority: str
    created_at: str
    scheduled_for: Optional[str] = None
    sent: bool = False
    metadata: Optional[Dict[str, Any]] = None


class NotificationSystem:
    """Simple file-based notification system"""
    
    def __init__(self, storage_path: str = "notifications.json"):
        self.storage_path = storage_path
        self.notifications: List[Notification] = []
        self.load_notifications()
    
    def load_notifications(self):
        """Load notifications from storage"""
        if os.path.exists(self.storage_path):
            try:
                with open(self.storage_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.notifications = [
                        Notification(**item) for item in data
                    ]
            except Exception:
                self.notifications = []
    
    def save_notifications(self):
        """Save notifications to storage"""
        try:
            with open(self.storage_path, 'w', encoding='utf-8') as f:
                json.dump([asdict(n) for n in self.notifications], f, indent=2)
        except Exception:
            pass
    
    def create_notification(
        self,
        recipient_id: str,
        message: str,
        notification_type: str,
        priority: str = "medium",
        scheduled_for: Optional[datetime] = None,
        metadata: Optional[Dict[str, Any]] = None
    ) -> str:
        """Create a new notification"""
        notification_id = f"notif_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{len(self.notifications)}"
        
        notification = Notification(
            id=notification_id,
            recipient_id=recipient_id,
            message=message,
            notification_type=notification_type,
            priority=priority,
            created_at=datetime.now().isoformat(),
            scheduled_for=scheduled_for.isoformat() if scheduled_for else None,
            metadata=metadata or {}
        )
        
        self.notifications.append(notification)
        self.save_notifications()
        return notification_id
    
    def get_pending_notifications(self, recipient_id: Optional[str] = None) -> List[Notification]:
        """Get pending notifications"""
        current_time = datetime.now()
        pending = []
        
        for notification in self.notifications:
            if notification.sent:
                continue
                
            if recipient_id and notification.recipient_id != recipient_id:
                continue
                
            # Check if it's time to send
            if notification.scheduled_for:
                scheduled_time = datetime.fromisoformat(notification.scheduled_for)
                if scheduled_time > current_time:
                    continue
            
            pending.append(notification)
        
        return pending
    
    def mark_as_sent(self, notification_id: str):
        """Mark notification as sent"""
        for notification in self.notifications:
            if notification.id == notification_id:
                notification.sent = True
                break
        self.save_notifications()
    
    def get_notification_summary(self) -> Dict[str, Any]:
        """Get summary of notifications"""
        total = len(self.notifications)
        sent = len([n for n in self.notifications if n.sent])
        pending = total - sent
        
        by_priority = {}
        for notification in self.notifications:
            if not notification.sent:
                priority = notification.priority
                by_priority[priority] = by_priority.get(priority, 0) + 1
        
        return {
            "total_notifications": total,
            "sent": sent,
            "pending": pending,
            "by_priority": by_priority,
            "last_updated": datetime.now().isoformat()
        }


# Global notification system instance
notification_system = NotificationSystem()


def create_task_reminder(
    task_id: str,
    task_name: str,
    reminder_type: str,
    recipient_id: str = "user",
    hours_ahead: int = 24
) -> str:
    """Create a task reminder notification"""
    scheduled_time = datetime.now() + timedelta(hours=hours_ahead)
    
    message_templates = {
        "deadline": f"Task '{task_name}' is due soon. Please review your progress.",
        "start": f"It's time to start working on task '{task_name}'.",
        "progress": f"Please update progress for task '{task_name}'."
    }
    
    message = message_templates.get(reminder_type, f"Reminder for task '{task_name}'")
    
    return notification_system.create_notification(
        recipient_id=recipient_id,
        message=message,
        notification_type="task_reminder",
        priority="medium",
        scheduled_for=scheduled_time,
        metadata={
            "task_id": task_id,
            "task_name": task_name,
            "reminder_type": reminder_type
        }
    )
