"""
Windows Clipboard Monitor Implementation
"""

import time
import hashlib
import re
from typing import List, Dict, Any
from .base import ClipboardMonitor


class WindowsClipboardMonitor(ClipboardMonitor):
    """
    Windows clipboard monitor implementation
    """
    
    def __init__(self):
        """Initialize the Windows clipboard monitor"""
        super().__init__()
        
    def monitor(self, duration: int = 60, interval: float = 1.0) -> List[Dict[str, Any]]:
        """
        Monitor clipboard for specified duration
        
        Args:
            duration: Monitoring duration in seconds
            interval: Check interval in seconds
            
        Returns:
            List of clipboard entries
        """
        if not self._check_permissions():
            return []
            
        clipboard_history = []
        last_content_hash = ""
        start_time = time.time()
        
        print(f"Monitoring clipboard for {duration} seconds...")
        
        while time.time() - start_time < duration:
            try:
                current_content = self.get_current_content()
                
                if current_content and current_content.get("text"):
                    content_hash = hashlib.md5(current_content["text"].encode('utf-8')).hexdigest()
                    
                    if content_hash != last_content_hash:
                        # Check for sensitive data
                        sensitive_data = self._detect_sensitive_data(current_content["text"])
                        
                        if sensitive_data:
                            current_content["sensitive_data"] = sensitive_data
                            current_content["has_sensitive_data"] = True
                        
                        clipboard_history.append(current_content)
                        last_content_hash = content_hash
                        
                        if sensitive_data:
                            print(f"Sensitive data detected: {sensitive_data}")
                            
            except Exception as e:
                print(f"Error reading clipboard: {e}")
                
            time.sleep(interval)
            
        # Save results
        if clipboard_history:
            self._save_results(clipboard_history, f"clipboard_history_{int(time.time())}.json")
            
        return clipboard_history
    
    def get_current_content(self) -> Dict[str, Any]:
        """
        Get current clipboard content
        
        Returns:
            Current clipboard content
        """
        try:
            import win32clipboard
            
            content = {
                "timestamp": time.time(),
                "text": "",
                "has_text": False,
                "has_image": False,
                "has_files": False
            }
            
            win32clipboard.OpenClipboard()
            
            # Check for text content
            if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_UNICODETEXT):
                try:
                    text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
                    if text:
                        content["text"] = text
                        content["has_text"] = True
                except:
                    pass
                    
            # Check for text content (ASCII)
            if not content["has_text"] and win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_TEXT):
                try:
                    text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
                    if text:
                        content["text"] = text
                        content["has_text"] = True
                except:
                    pass
                    
            # Check for file drops
            if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_HDROP):
                try:
                    files = win32clipboard.GetClipboardData(win32clipboard.CF_HDROP)
                    content["has_files"] = True
                    content["file_count"] = len(files) if files else 0
                except:
                    pass
                    
            # Check for images
            if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_BITMAP):
                content["has_image"] = True
                
            win32clipboard.CloseClipboard()
            
            return content
            
        except ImportError:
            print("pywin32 module not available")
            return {}
        except Exception as e:
            print(f"Error accessing clipboard: {e}")
            return {}
    
    def get_monitor_type(self) -> str:
        """
        Get monitor type identifier
        
        Returns:
            "windows_clipboard"
        """
        return "windows_clipboard"
    
    def _detect_sensitive_data(self, text: str) -> List[Dict[str, Any]]:
        """
        Detect sensitive data patterns in text
        
        Args:
            text: Text to analyze
            
        Returns:
            List of detected sensitive data patterns
        """
        if not text:
            return []
            
        sensitive_matches = []
        
        # Define detection patterns
        patterns = {
            "email": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b",
            "phone": r"\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b",
            "credit_card": r"\b(?:\d{4}[- ]?){3}\d{4}\b",
            "ssn": r"\b\d{3}[-]?\d{2}[-]?\d{4}\b",
            "api_key": r"\b(?:api[_-]?key|apikey|secret[_-]?key)\s*[=:]\s*[\w-]{20,}\b",
            "password": r"\b(?:password|passwd|pwd)\s*[=:]\s*\S+\b",
            "private_key": r"-----BEGIN (?:RSA |EC )?PRIVATE KEY-----",
            "aws_key": r"\b(?:AKIA|ABIA|ACCA)[A-Z0-9]{16}\b",
            "bearer_token": r"\bBearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\b"
        }
        
        for pattern_name, pattern in patterns.items():
            matches = re.findall(pattern, text, re.IGNORECASE)
            
            if matches:
                # Sanitize the sample (don't expose actual sensitive data)
                sample = matches[0]
                if pattern_name in ["api_key", "aws_key", "bearer_token", "private_key"]:
                    sample = "[REDACTED]"
                elif pattern_name == "password":
                    # Extract just the key part, not the value
                    if "=" in sample or ":" in sample:
                        sample = sample.split("=")[0] if "=" in sample else sample.split(":")[0]
                
                sensitive_matches.append({
                    "type": pattern_name,
                    "count": len(matches),
                    "sample": sample
                })
                
        return sensitive_matches