#!/usr/bin/env python3
"""
===================================
TEMPORAL BACKUP SYSTEM - NOTIFIER
===================================

Sistema de notificações para Temporal Backup System
Monitora backups e envia alertas via macOS notifications

Features:
- Monitor rotações automáticas
- Alertas de backups bem-sucedidos
- Warnings para backups grandes
- Notificações de erros

Usage:
    python3 backup-notifier.py

Requirements:
    - macOS
    - Python 3.6+
"""

import json
import time
import os
import subprocess
from datetime import datetime, timedelta
from pathlib import Path

# Configuration
CHECK_INTERVAL = 60  # Check every 60 seconds
NOTIFICATION_COOLDOWN = 300  # Don't spam (5 min between similar notifications)
LARGE_BACKUP_THRESHOLD_KB = 5000  # 5 MB

# Track last notifications
last_notifications = {}


def send_notification(title, message, sound="default"):
    """Send macOS notification"""
    try:
        script = f'''
        display notification "{message}" with title "{title}" sound name "{sound}"
        '''
        subprocess.run(["osascript", "-e", script], check=True, capture_output=True)
        print(f"[{datetime.now().strftime('%H:%M:%S')}] 📬 {title}: {message}")
    except Exception as e:
        print(f"[{datetime.now().strftime('%H:%M:%S')}] ❌ Notification error: {e}")


def should_send_notification(notification_key):
    """Check if enough time passed since last similar notification"""
    now = time.time()
    if notification_key not in last_notifications:
        last_notifications[notification_key] = now
        return True

    elapsed = now - last_notifications[notification_key]
    if elapsed > NOTIFICATION_COOLDOWN:
        last_notifications[notification_key] = now
        return True

    return False


def get_backup_stats():
    """Get backup statistics from localStorage simulation"""
    # In a real implementation, this would read from localStorage
    # For now, we'll simulate by checking file sizes
    stats = {
        'active_backups': 0,
        'total_size_kb': 0,
        'last_rotation': None,
        'backups': []
    }

    # Check for backup files (simulated)
    backup_dir = Path.home()
    patterns = ['tbs_*_daily', 'tbs_*_weekly', 'tbs_*_monthly']

    # Note: This is a simplified version
    # In production, you'd integrate with the actual localStorage data
    # via a web API or browser extension

    return stats


def check_for_rotations():
    """Check if rotation occurred recently"""
    now = datetime.now()

    # Check daily rotation (midnight)
    if now.hour == 0 and now.minute < 5:
        if should_send_notification('daily_rotation'):
            send_notification(
                "🔄 Rotação Diária",
                "Backup diário foi rotacionado às 00:00",
                "Glass"
            )

    # Check weekly rotation (Sunday)
    if now.weekday() == 6 and now.hour == 0 and now.minute < 5:
        if should_send_notification('weekly_rotation'):
            send_notification(
                "🔄 Rotação Semanal",
                "Backup semanal foi rotacionado no domingo",
                "Glass"
            )

    # Check monthly rotation (1st day)
    if now.day == 1 and now.hour == 0 and now.minute < 5:
        if should_send_notification('monthly_rotation'):
            send_notification(
                "🔄 Rotação Mensal",
                f"Backup mensal foi rotacionado em {now.strftime('%B')}",
                "Glass"
            )


def check_backup_health():
    """Check backup health and send warnings if needed"""
    stats = get_backup_stats()

    # Check if backups are active
    if stats['active_backups'] == 0:
        if should_send_notification('no_backups'):
            send_notification(
                "⚠️ Aviso de Backup",
                "Nenhum backup ativo encontrado",
                "Basso"
            )
        return

    # Check for large backups
    if stats['total_size_kb'] > LARGE_BACKUP_THRESHOLD_KB:
        if should_send_notification('large_backup'):
            size_mb = stats['total_size_kb'] / 1024
            send_notification(
                "💾 Backup Grande",
                f"Backups ocupando {size_mb:.1f} MB. Considere exportar/limpar.",
                "Funk"
            )


def monitor_backup_activity():
    """Monitor backup activity via log files"""
    # This would monitor actual backup logs
    # For demo, we'll just check timestamps

    log_file = Path.home() / ".temporal-backup.log"

    if not log_file.exists():
        return

    try:
        with open(log_file, 'r') as f:
            lines = f.readlines()
            if len(lines) > 0:
                last_line = lines[-1]
                if "Backup created" in last_line:
                    timestamp = last_line.split('[')[1].split(']')[0]
                    if should_send_notification('backup_created'):
                        send_notification(
                            "✅ Backup Criado",
                            f"Novo backup salvo às {timestamp}",
                            "Purr"
                        )
    except Exception as e:
        print(f"[{datetime.now().strftime('%H:%M:%S')}] ❌ Log read error: {e}")


def run_monitor():
    """Main monitoring loop"""
    print("=" * 50)
    print("🗄️  TEMPORAL BACKUP SYSTEM - NOTIFIER")
    print("=" * 50)
    print(f"Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"Check interval: {CHECK_INTERVAL}s")
    print(f"Notification cooldown: {NOTIFICATION_COOLDOWN}s")
    print("=" * 50)
    print("")

    # Initial notification
    send_notification(
        "🗄️ Backup Monitor",
        "Sistema de monitoramento de backups iniciado",
        "Submarine"
    )

    iteration = 0

    try:
        while True:
            iteration += 1
            print(f"[{datetime.now().strftime('%H:%M:%S')}] 🔍 Check #{iteration}")

            # Check for rotations
            check_for_rotations()

            # Check backup health
            check_backup_health()

            # Monitor activity
            monitor_backup_activity()

            # Wait for next check
            time.sleep(CHECK_INTERVAL)

    except KeyboardInterrupt:
        print("\n")
        print("=" * 50)
        print("⏹️  Monitor stopped by user")
        print("=" * 50)
        send_notification(
            "⏹️ Backup Monitor",
            "Sistema de monitoramento de backups parado",
            "Tink"
        )


def test_notifications():
    """Test notification system"""
    print("Testing notification system...")
    print("")

    tests = [
        ("✅ Sucesso", "Teste de notificação de sucesso", "Purr"),
        ("⚠️ Aviso", "Teste de notificação de aviso", "Basso"),
        ("❌ Erro", "Teste de notificação de erro", "Sosumi"),
        ("🔄 Rotação", "Teste de notificação de rotação", "Glass"),
    ]

    for title, message, sound in tests:
        send_notification(title, message, sound)
        time.sleep(2)

    print("")
    print("✅ Teste concluído!")


if __name__ == "__main__":
    import sys

    if len(sys.argv) > 1 and sys.argv[1] == "--test":
        test_notifications()
    else:
        run_monitor()
