"""Logging unsubscribe attempts to markdown file."""
import os
from datetime import datetime
from typing import Dict, List
from pathlib import Path


class UnsubscribeLogger:
    """Logger for unsubscribe attempts."""
    
    def __init__(self, log_file: str = None):
        """
        Inicjalizacja loggera.
        
        Args:
            log_file: Ścieżka do pliku unsubscribe.md
        """
        self.log_file = log_file or os.path.join(os.getcwd(), 'unsubscribe.md')
        self._ensure_file_exists()
    
    def _ensure_file_exists(self):
        """Tworzy plik jeśli nie istnieje."""
        if not os.path.exists(self.log_file):
            with open(self.log_file, 'w', encoding='utf-8') as f:
                f.write('# Unsubscribe Log\n\n')
                f.write('Rejestr prób wypisania się z newsletterów.\n\n')
                f.write('---\n\n')
    
    def log_attempt(self, result: Dict):
        """
        Loguje pojedynczą próbę wypisania.
        
        Args:
            result: Słownik z rezultatem (z UnsubscribeBrowser.unsubscribe)
        """
        email_info = result.get('email_info', {})
        success = result.get('success', False)
        message = result.get('message', '')
        screenshots = result.get('screenshots', [])
        timestamp = result.get('timestamp', datetime.now().isoformat())
        
        with open(self.log_file, 'a', encoding='utf-8') as f:
            # Header
            status_emoji = '✅' if success else '❌'
            f.write(f"## {status_emoji} {email_info.get('sender', 'Unknown')}\n\n")
            
            # Metadata
            f.write(f"**Data próby**: {timestamp}\n\n")
            f.write(f"**Status**: {message}\n\n")
            f.write(f"**Email od**: {email_info.get('sender', 'Unknown')}\n\n")
            f.write(f"**Temat**: {email_info.get('subject', 'No subject')}\n\n")
            f.write(f"**Data emaila**: {email_info.get('date', 'Unknown')}\n\n")
            f.write(f"**URL**: {result.get('url', 'N/A')}\n\n")
            
            # Body fragment
            if email_info.get('body_fragment'):
                f.write("**Fragment wiadomości**:\n")
                f.write("```\n")
                f.write(email_info['body_fragment'][:500])
                f.write("\n```\n\n")
            
            # Screenshots
            if screenshots:
                f.write("**Zrzuty ekranu**:\n\n")
                for i, screenshot in enumerate(screenshots, 1):
                    # Use relative path if possible
                    rel_path = os.path.relpath(screenshot, os.path.dirname(self.log_file))
                    f.write(f"{i}. ![Screenshot {i}]({rel_path})\n")
                f.write("\n")
            
            f.write("---\n\n")
    
    def log_batch(self, results: List[Dict]):
        """
        Loguje wiele prób wypisania.
        
        Args:
            results: Lista słowników z rezultatami
        """
        # Add summary section
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        success_count = sum(1 for r in results if r.get('success'))
        fail_count = len(results) - success_count
        
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(f"# Sesja: {timestamp}\n\n")
            f.write(f"**Podsumowanie**: {success_count} sukces(ów), {fail_count} niepowodzeń\n\n")
            f.write("---\n\n")
        
        # Log individual attempts
        for result in results:
            self.log_attempt(result)
    
    def get_failed_senders(self) -> List[str]:
        """
        Pobiera listę nadawców, z którymi nie udało się wypisać.
        
        Returns:
            Lista adresów email nadawców
        """
        if not os.path.exists(self.log_file):
            return []
        
        failed_senders = []
        
        with open(self.log_file, 'r', encoding='utf-8') as f:
            content = f.read()
            
            # Find all failed attempts
            import re
            failed_sections = re.findall(r'## ❌.*?\n\n.*?Email od\*\*: (.+?)\n', content, re.DOTALL)
            failed_senders.extend(failed_sections)
        
        return list(set(failed_senders))  # Remove duplicates
    
    def generate_stats(self) -> Dict:
        """
        Generuje statystyki z loga.
        
        Returns:
            Słownik ze statystykami
        """
        if not os.path.exists(self.log_file):
            return {'total': 0, 'success': 0, 'failed': 0, 'success_rate': 0}
        
        with open(self.log_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        import re
        success_count = len(re.findall(r'## ✅', content))
        failed_count = len(re.findall(r'## ❌', content))
        total = success_count + failed_count
        
        stats = {
            'total': total,
            'success': success_count,
            'failed': failed_count,
            'success_rate': round(success_count / total * 100, 1) if total > 0 else 0,
        }
        
        return stats
