"""
Preview Generator utility for creating document previews and thumbnails.
Extracted from document_base.py PreviewGenerator class.
"""
import os
from pathlib import Path
from typing import Optional, Tuple
from PIL import Image


class PreviewGenerator:
    """
    Utility class for generating preview images and thumbnails from documents.
    """
    
    def __init__(self, output_folder: str = "document_images"):
        self.output_folder = output_folder
        Path(output_folder).mkdir(parents=True, exist_ok=True)
    
    def generate_preview(self, file_path: str, file_type: str, 
                         file_id: str) -> Tuple[Optional[str], Optional[str]]:
        """
        Generate preview and thumbnail for a file.
        
        Returns:
            Tuple of (image_path, thumbnail_path) or (None, None) if not supported
        """
        generators = {
            'pdf': self._generate_pdf_preview,
            'png': self._generate_image_preview,
            'jpg': self._generate_image_preview,
            'jpeg': self._generate_image_preview,
        }
        
        generator = generators.get(file_type)
        if generator:
            return generator(file_path, file_id)
        return None, None
    
    def _generate_pdf_preview(self, file_path: str, 
                              file_id: str) -> Tuple[Optional[str], Optional[str]]:
        """Generate preview from PDF first page"""
        try:
            import pymupdf
            doc = pymupdf.open(file_path)
            page = doc[0]
            
            mat = pymupdf.Matrix(2, 2)
            pix = page.get_pixmap(matrix=mat)
            img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
            
            image_path = os.path.join(self.output_folder, f"{file_id}_preview.png")
            img.save(image_path, "PNG", optimize=True)
            
            thumbnail = img.copy()
            thumbnail.thumbnail((400, 400), Image.Resampling.LANCZOS)
            thumbnail_path = os.path.join(self.output_folder, f"{file_id}_thumb.png")
            thumbnail.save(thumbnail_path, "PNG", optimize=True)
            
            doc.close()
            return image_path, thumbnail_path
        except ImportError:
            print("pymupdf is required for PDF preview generation")
            return None, None
        except Exception as e:
            print(f"Error generating PDF preview: {e}")
            return None, None
    
    def _generate_image_preview(self, file_path: str, 
                                file_id: str) -> Tuple[Optional[str], Optional[str]]:
        """Generate preview from image file"""
        try:
            img = Image.open(file_path)
            
            if img.mode not in ('RGB', 'RGBA'):
                img = img.convert('RGB')
            
            image_path = os.path.join(self.output_folder, f"{file_id}_preview.png")
            img.save(image_path, "PNG", optimize=True)
            
            thumbnail = img.copy()
            thumbnail.thumbnail((400, 400), Image.Resampling.LANCZOS)
            thumbnail_path = os.path.join(self.output_folder, f"{file_id}_thumb.png")
            thumbnail.save(thumbnail_path, "PNG", optimize=True)
            
            return image_path, thumbnail_path
        except Exception as e:
            print(f"Error generating image preview: {e}")
            return None, None
