"""
Member Card Generator using Pillow
Overlays user data on CANVA-designed card templates
"""
from PIL import Image, ImageDraw, ImageFont, ImageOps
from io import BytesIO
import qrcode
from django.conf import settings
import os


class MemberCardGenerator:
    """Generate member cards by overlaying user data on CANVA templates"""
    
    def __init__(self, user_profile, card_config):
        """
        Initialize card generator
        
        Args:
            user_profile: UserProfile instance
            card_config: MemberCardConfig instance
        """
        self.profile = user_profile
        self.config = card_config
        self.card_template = None
        
        # Determine which template to use
        if user_profile.giving_circle and user_profile.giving_circle.card_template:
            self.card_template = user_profile.giving_circle.card_template
        else:
            # Use default template (first active one)
            from .models import CardTemplate
            self.card_template = CardTemplate.objects.filter(is_active=True).first()
    
    def generate_card(self):
        """
        Generate the complete member card image
        
        Returns:
            PIL.Image: Generated card image
        """
        if not self.card_template or not self.card_template.template_image:
            raise ValueError("No card template available")
        
        # Load base template
        card = Image.open(self.card_template.template_image.path).convert('RGB')
        
        # Create drawing context
        draw = ImageDraw.Draw(card)
        
        # Add user name
        self._add_user_name(draw)
        
        # Add generation code
        self._add_generation_code(draw)
        
        # Add user photo
        self._add_user_photo(card)
        
        # Add QR codes
        self._add_qr_codes(card)
        
        return card
    
    def _add_user_name(self, draw):
        """Add user's full name to the card"""
        name = self.profile.user.get_full_name() or self.profile.user.username
        
        # Load font
        try:
            # Try to use a bold font
            font = ImageFont.truetype(
                self._get_font_path('arial-bold.ttf'),
                self.card_template.name_font_size
            )
        except:
            # Fallback to default
            font = ImageFont.load_default()
        
        # Convert hex color to RGB
        color = self._hex_to_rgb(self.card_template.name_color)
        
        # Draw text
        draw.text(
            (self.card_template.name_x, self.card_template.name_y),
            name.upper(),
            fill=color,
            font=font
        )
    
    def _add_generation_code(self, draw):
        """Add generation code to the card"""
        if not self.profile.generation_code:
            return
        
        # Load font
        try:
            font = ImageFont.truetype(
                self._get_font_path('arial.ttf'),
                self.card_template.code_font_size
            )
        except:
            font = ImageFont.load_default()
        
        # Convert hex color to RGB
        color = self._hex_to_rgb(self.card_template.code_color)
        
        # Draw text
        draw.text(
            (self.card_template.code_x, self.card_template.code_y),
            self.profile.generation_code,
            fill=color,
            font=font
        )
    
    def _add_user_photo(self, card):
        """Add user's profile photo to the card"""
        if not self.profile.photo:
            return
        
        try:
            # Open and resize photo
            photo = Image.open(self.profile.photo.path).convert('RGB')
            
            # Create circular mask
            size = (self.card_template.photo_size, self.card_template.photo_size)
            photo = photo.resize(size, Image.Resampling.LANCZOS)
            
            # Create circular mask
            mask = Image.new('L', size, 0)
            mask_draw = ImageDraw.Draw(mask)
            mask_draw.ellipse((0, 0) + size, fill=255)
            
            # Apply circular mask
            output = ImageOps.fit(photo, size, centering=(0.5, 0.5))
            output.putalpha(mask)
            
            # Paste onto card
            card.paste(
                output,
                (self.card_template.photo_x, self.card_template.photo_y),
                output
            )
        except Exception as e:
            print(f"Error adding photo: {e}")
    
    def _add_qr_codes(self, card):
        """Add QR codes to the card"""
        # QR Code 1 (Donation)
        qr1 = self._generate_qr_code(
            self.config.qr_code_1_url,
            self.card_template.qr_size
        )
        card.paste(
            qr1,
            (self.card_template.qr1_x, self.card_template.qr1_y)
        )
        
        # QR Code 2 (Website)
        qr2 = self._generate_qr_code(
            self.config.qr_code_2_url,
            self.card_template.qr_size
        )
        card.paste(
            qr2,
            (self.card_template.qr2_x, self.card_template.qr2_y)
        )
    
    def _generate_qr_code(self, url, size):
        """
        Generate a QR code image
        
        Args:
            url: URL to encode
            size: Size in pixels
            
        Returns:
            PIL.Image: QR code image
        """
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_M,
            box_size=10,
            border=1,
        )
        qr.add_data(url)
        qr.make(fit=True)
        
        qr_image = qr.make_image(fill_color="black", back_color="white")
        qr_image = qr_image.resize((size, size), Image.Resampling.LANCZOS)
        
        return qr_image
    
    def _hex_to_rgb(self, hex_color):
        """Convert hex color to RGB tuple"""
        hex_color = hex_color.lstrip('#')
        return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
    
    def _get_font_path(self, font_name):
        """Get system font path"""
        # Common font paths on different systems
        font_paths = [
            f'/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',  # Linux
            f'/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf',  # Linux
            f'/System/Library/Fonts/Helvetica.ttc',  # macOS
            f'C:\\Windows\\Fonts\\arial.ttf',  # Windows
        ]
        
        for path in font_paths:
            if os.path.exists(path):
                return path
        
        # Fallback to default
        raise IOError("No suitable font found")
    
    def save_to_bytes(self, format='PNG'):
        """
        Generate card and save to bytes buffer
        
        Args:
            format: Image format (PNG, JPEG)
            
        Returns:
            BytesIO: Image bytes buffer
        """
        card = self.generate_card()
        buffer = BytesIO()
        card.save(buffer, format=format, quality=95)
        buffer.seek(0)
        return buffer
    
    def save_to_file(self, file_path, format='PNG'):
        """
        Generate card and save to file
        
        Args:
            file_path: Path to save the image
            format: Image format (PNG, JPEG)
        """
        card = self.generate_card()
        card.save(file_path, format=format, quality=95)
