"""Browser automation for unsubscribe process."""
import os
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional, Tuple, List

try:
    from playwright.sync_api import sync_playwright, Page, Browser
    PLAYWRIGHT_AVAILABLE = True
except ImportError:
    sync_playwright = None
    Page = None
    Browser = None
    PLAYWRIGHT_AVAILABLE = False


class UnsubscribeBrowser:
    """Automated browser for unsubscribe process."""
    
    def __init__(self, screenshots_dir: str = None, headless: bool = True):
        """
        Inicjalizacja przeglądarki.
        
        Args:
            screenshots_dir: Katalog do zapisywania zrzutów ekranu
            headless: Czy uruchomić przeglądarkę w trybie headless
        """
        if not PLAYWRIGHT_AVAILABLE:
            raise ImportError("Playwright not available. Install: pip install playwright && playwright install chromium")
        
        self.screenshots_dir = screenshots_dir or os.path.join(os.getcwd(), 'unsubscribe_screenshots')
        Path(self.screenshots_dir).mkdir(parents=True, exist_ok=True)
        
        self.headless = headless
        self.playwright = None
        self.browser = None
        self.context = None
    
    def __enter__(self):
        """Context manager entry."""
        self.playwright = sync_playwright().start()
        self.browser = self.playwright.chromium.launch(headless=self.headless)
        self.context = self.browser.new_context(
            viewport={'width': 1920, 'height': 1080},
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        )
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """Context manager exit."""
        if self.context:
            self.context.close()
        if self.browser:
            self.browser.close()
        if self.playwright:
            self.playwright.stop()
    
    def _save_screenshot(self, page: Page, name: str) -> str:
        """Zapisuje zrzut ekranu."""
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"{name}_{timestamp}.png"
        filepath = os.path.join(self.screenshots_dir, filename)
        page.screenshot(path=filepath, full_page=True)
        return filepath
    
    def unsubscribe(self, url: str, email_info: Dict, open_in_browser: bool = False) -> Tuple[bool, str, List[str]]:
        """
        Próbuje wypisać się z newslettera.
        
        Args:
            url: URL do unsubscribe
            email_info: Informacje o emailu (sender, subject, date)
            open_in_browser: Czy otworzyć link również w domyślnej przeglądarce (nowy tab)
        
        Returns:
            Tuple (success, message, screenshot_paths)
        """
        screenshots = []
        
        # Open in default browser if requested
        if open_in_browser:
            try:
                import webbrowser
                webbrowser.open_new_tab(url)
                print(f"🌐 Otwarto w przeglądarce: {url}")
            except Exception as e:
                print(f"⚠️  Nie można otworzyć w przeglądarce: {e}")
        
        page = self.context.new_page()
        
        try:
            print(f"🤖 Automatyczne unsubscribe: {url}")
            
            # 1. Navigate to unsubscribe page
            try:
                response = page.goto(url, wait_until='networkidle', timeout=30000)
                if response.status >= 400:
                    return False, f"HTTP {response.status}", []
            except Exception as e:
                return False, f"Nie można otworzyć strony: {str(e)}", []
            
            # Screenshot 1: Initial page
            screenshot1 = self._save_screenshot(page, 'step1_initial')
            screenshots.append(screenshot1)
            print(f"📸 Zrzut 1: {screenshot1}")
            
            # 1.5. Handle cookie consent dialogs first
            cookie_selectors = [
                # Accept buttons
                'button:has-text("Alle ablehnen")',  # Reject all (Workwise)
                'button:has-text("Reject all")',
                'button:has-text("Odrzuć wszystko")',
                'button:has-text("Accept")',
                'button:has-text("Akzeptieren")',
                'button:has-text("Akceptuj")',
                'button:has-text("OK")',
                # Close buttons
                'button[aria-label="Close"]',
                'button.cookie-close',
                '[id*="cookie"] button',
                '[class*="cookie"] button',
                '[class*="consent"] button',
            ]
            
            for selector in cookie_selectors:
                try:
                    if page.locator(selector).count() > 0:
                        print(f"🍪 Zamykam cookie dialog: {selector}")
                        page.locator(selector).first.click(timeout=3000)
                        page.wait_for_timeout(1000)  # Wait for dialog to close
                        break
                except Exception:
                    continue
            
            # 2. Look for unsubscribe button/link
            unsubscribe_selectors = [
                # Common button text
                'button:has-text("Unsubscribe")',
                'button:has-text("Confirm")',
                'button:has-text("Yes")',
                'button:has-text("Wypisz")',
                'button:has-text("Potwierdź")',
                'button:has-text("Tak")',
                'button:has-text("Abmelden")',
                'button:has-text("Bestätigen")',
                # Links
                'a:has-text("Unsubscribe")',
                'a:has-text("Click here")',
                'a:has-text("Wypisz")',
                'a:has-text("Kliknij tutaj")',
                # Inputs
                'input[type="submit"][value*="unsubscribe" i]',
                'input[type="submit"][value*="confirm" i]',
                'input[type="submit"][value*="wypisz" i]',
                # Generic
                'button[type="submit"]',
                'input[type="submit"]',
            ]
            
            clicked = False
            for selector in unsubscribe_selectors:
                try:
                    if page.locator(selector).count() > 0:
                        print(f"🔍 Znaleziono: {selector}")
                        page.locator(selector).first.click(timeout=5000)
                        clicked = True
                        page.wait_for_load_state('networkidle', timeout=10000)
                        break
                except Exception:
                    continue
            
            if not clicked:
                # Try to find any prominent button
                try:
                    buttons = page.locator('button, input[type="submit"]')
                    if buttons.count() > 0:
                        print(f"🔍 Klikam pierwszy przycisk")
                        buttons.first.click(timeout=5000)
                        page.wait_for_load_state('networkidle', timeout=10000)
                        clicked = True
                except Exception:
                    pass
            
            # Screenshot 2: After click
            screenshot2 = self._save_screenshot(page, 'step2_after_click')
            screenshots.append(screenshot2)
            print(f"📸 Zrzut 2: {screenshot2}")
            
            # 3. Check for success messages
            page_content = page.content().lower()
            success_keywords = [
                'successfully unsubscribed',
                'you have been unsubscribed',
                'wypisano pomyślnie',
                'zostałeś wypisany',
                'erfolgreich abgemeldet',
                'désabonné avec succès',
                'successfully removed',
                'unsubscribed successfully',
            ]
            
            is_success = any(keyword in page_content for keyword in success_keywords)
            
            # Look for success messages in visible text
            try:
                body_text = page.locator('body').inner_text().lower()
                if not is_success:
                    is_success = any(keyword in body_text for keyword in success_keywords)
            except Exception:
                pass
            
            if is_success:
                return True, "✅ Wypisano pomyślnie", screenshots
            elif clicked:
                return True, "⚠️ Kliknięto przycisk (niepotwierdzony sukces)", screenshots
            else:
                return False, "❌ Nie znaleziono przycisku unsubscribe", screenshots
            
        except Exception as e:
            screenshot_error = self._save_screenshot(page, 'error')
            screenshots.append(screenshot_error)
            return False, f"❌ Błąd: {str(e)}", screenshots
        
        finally:
            page.close()
    
    def batch_unsubscribe(self, urls_with_info: List[Tuple[str, Dict]], 
                          open_in_browser: bool = False) -> List[Dict]:
        """
        Wypisuje się z wielu newsletterów.
        
        Args:
            urls_with_info: Lista tupli (url, email_info)
            open_in_browser: Czy otworzyć linki również w domyślnej przeglądarce
        
        Returns:
            Lista wyników dla każdego URL
        """
        results = []
        
        for url, email_info in urls_with_info:
            print(f"\n{'='*60}")
            print(f"📧 Od: {email_info.get('sender', 'Unknown')}")
            print(f"📋 Temat: {email_info.get('subject', 'No subject')}")
            print(f"🔗 URL: {url}")
            
            success, message, screenshots = self.unsubscribe(url, email_info, open_in_browser)
            
            result = {
                'url': url,
                'email_info': email_info,
                'success': success,
                'message': message,
                'screenshots': screenshots,
                'timestamp': datetime.now().isoformat(),
            }
            
            results.append(result)
            
            print(f"📊 Rezultat: {message}")
            if screenshots:
                print(f"📸 Zrzuty: {len(screenshots)} plik(ów)")
        
        return results
