# pdf_generator_server.py - COMPLETE WORKING VERSION
import os
import sys
import json
import uuid
import tempfile
import subprocess
from datetime import datetime
import traceback
from flask import Flask, request, jsonify, Response
from flask_cors import CORS
import base64
from PIL import Image
import io
import imghdr

app = Flask(__name__)
CORS(app)

# Configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMP_DIR = os.path.join(BASE_DIR, "temp_pdfs")
os.makedirs(TEMP_DIR, exist_ok=True)

# WKHTMLTOPDF Configuration
WKHTMLTOPDF_PATH = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe"

class PDFGenerator:
    def __init__(self):
        self.check_wkhtmltopdf()
    
    def check_wkhtmltopdf(self):
        """Check if wkhtmltopdf is installed"""
        try:
            result = subprocess.run(
                [WKHTMLTOPDF_PATH, '--version'],
                capture_output=True,
                text=True,
                timeout=5
            )
            if result.returncode == 0:
                print(f"✅ wkhtmltopdf found: {result.stdout.strip()}")
                return True
        except:
            pass
        print("❌ wkhtmltopdf not found")
        return False
    
    def convert_image_for_pdf(self, image_path):
        """Convert any image to JPEG format for PDF compatibility"""
        try:
            if not os.path.exists(image_path):
                print(f"❌ Image not found: {image_path}")
                return None
            
            # Open and convert image
            img = Image.open(image_path)
            
            # Convert to RGB if necessary
            if img.mode in ('RGBA', 'LA', 'P'):
                # Create white background for transparency
                if img.mode == 'P':
                    img = img.convert('RGBA')
                
                background = Image.new('RGB', img.size, (255, 255, 255))
                
                if img.mode == 'RGBA':
                    # Paste with alpha channel
                    background.paste(img, mask=img.split()[3])
                else:
                    background.paste(img)
                
                img = background
            elif img.mode != 'RGB':
                img = img.convert('RGB')
            
            # Resize if too large (max 1000px height)
            max_height = 1000
            if img.height > max_height:
                ratio = max_height / img.height
                new_width = int(img.width * ratio)
                img = img.resize((new_width, max_height), Image.Resampling.LANCZOS)
            
            # Save to bytes as JPEG
            img_bytes = io.BytesIO()
            img.save(img_bytes, format='JPEG', quality=85, optimize=True)
            jpeg_data = img_bytes.getvalue()
            
            print(f"✅ Converted {os.path.basename(image_path)} to JPEG ({len(jpeg_data)} bytes)")
            return jpeg_data
            
        except Exception as e:
            print(f"❌ Error converting image {image_path}: {e}")
            return None
    
    def generate_pdf(self, html_content, images_data, project_id):
        """Generate PDF from HTML with embedded images"""
        try:
            # Create temp HTML file with embedded images
            temp_html = self.create_html_with_images(html_content, images_data)
            
            # Generate PDF filename
            pdf_filename = f"portfolio_{project_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
            pdf_path = os.path.join(TEMP_DIR, pdf_filename)
            
            print(f"🔄 Generating PDF: {pdf_path}")
            
            # wkhtmltopdf options
            cmd = [
                WKHTMLTOPDF_PATH,
                '--page-size', 'Legal',
                '--orientation', 'Landscape',
                '--margin-top', '0.5in',
                '--margin-right', '0.5in',
                '--margin-bottom', '0.5in',
                '--margin-left', '0.5in',
                '--encoding', 'UTF-8',
                '--enable-local-file-access',
                '--quiet',
                '--print-media-type',
                temp_html,
                pdf_path
            ]
            
            # Run wkhtmltopdf
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=120
            )
            
            if result.returncode != 0:
                print(f"❌ wkhtmltopdf error: {result.stderr}")
                return None
            
            print(f"✅ PDF generated successfully: {pdf_path} ({os.path.getsize(pdf_path)} bytes)")
            
            # Read PDF content
            with open(pdf_path, 'rb') as f:
                pdf_content = f.read()
            
            # Cleanup
            os.remove(temp_html)
            os.remove(pdf_path)
            
            return pdf_content
            
        except Exception as e:
            print(f"❌ PDF generation error: {e}")
            traceback.print_exc()
            return None
    
    def create_html_with_images(self, html_content, images_data):
        """Create HTML file with embedded base64 images"""
        # Create a simple, clean HTML structure
        html_template = """
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>GO Productions Portfolio</title>
            <style>
                @page {
                    size: legal landscape;
                    margin: 0.5in;
                }
                
                body {
                    font-family: Arial, sans-serif;
                    margin: 0;
                    padding: 0;
                    background: white;
                }
                
                .page {
                    width: 100%;
                    min-height: 100vh;
                    page-break-after: always;
                    padding: 40px;
                    box-sizing: border-box;
                }
                
                .page:last-child {
                    page-break-after: avoid;
                }
                
                .header {
                    display: flex;
                    justify-content: space-between;
                    margin-bottom: 30px;
                }
                
                .model-name {
                    font-size: 48px;
                    font-weight: bold;
                    text-transform: uppercase;
                }
                
                .photo-grid {
                    display: grid;
                    grid-template-columns: repeat(3, 1fr);
                    gap: 10px;
                    margin: 20px 0;
                }
                
                .photo-container {
                    width: 100%;
                    height: 300px;
                    overflow: hidden;
                }
                
                .photo-container img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
                
                .footer {
                    margin-top: 30px;
                    padding-top: 20px;
                    border-top: 1px solid #ccc;
                    text-align: center;
                }
            </style>
        </head>
        <body>
            %CONTENT%
        </body>
        </html>
        """
        
        # Replace image placeholders with actual base64 images
        for img_data in images_data:
            image_path = img_data.get('image_path', '')
            if image_path and os.path.exists(image_path):
                # Convert image to base64
                jpeg_data = self.convert_image_for_pdf(image_path)
                if jpeg_data:
                    base64_str = base64.b64encode(jpeg_data).decode('utf-8')
                    # Replace image path with data URI in HTML
                    html_content = html_content.replace(
                        image_path, 
                        f"data:image/jpeg;base64,{base64_str}"
                    )
        
        # Insert content into template
        final_html = html_template.replace('%CONTENT%', html_content)
        
        # Save to temp file
        temp_file = tempfile.NamedTemporaryFile(
            mode='w', 
            suffix='.html', 
            encoding='utf-8', 
            delete=False
        )
        temp_file.write(final_html)
        temp_file.close()
        
        return temp_file.name

# Initialize generator
pdf_generator = PDFGenerator()

@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({
        'status': 'healthy',
        'wkhtmltopdf_available': pdf_generator.check_wkhtmltopdf(),
        'timestamp': datetime.now().isoformat()
    })

@app.route('/generate-pdf-from-preview', methods=['POST'])
def generate_pdf_from_preview():
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': 'No JSON data received'}), 400
        
        print("📨 Received PDF generation request")
        
        html_content = data.get('html_content', '')
        images_data = data.get('images_data', [])
        project_id = data.get('project_id', 'unknown')
        
        if not html_content:
            return jsonify({'error': 'No HTML content provided'}), 400
        
        print(f"📄 Processing {len(images_data)} images for project {project_id}")
        
        # Generate PDF
        pdf_content = pdf_generator.generate_pdf(html_content, images_data, project_id)
        
        if not pdf_content:
            return jsonify({'error': 'PDF generation failed'}), 500
        
        # Return PDF
        return Response(
            pdf_content,
            mimetype='application/pdf',
            headers={
                'Content-Disposition': f'attachment; filename="portfolio_{project_id}.pdf"',
                'Content-Length': str(len(pdf_content))
            }
        )
        
    except Exception as e:
        print(f"💥 Error: {str(e)}")
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    print("=== PDF GENERATOR SERVER ===")
    print(f"📁 Temp directory: {TEMP_DIR}")
    
    if pdf_generator.check_wkhtmltopdf():
        print("✅ Server ready on http://127.0.0.1:5001")
        app.run(host='127.0.0.1', port=5001, debug=False, threaded=True)
    else:
        print("❌ wkhtmltopdf not found. Please check installation.")
        sys.exit(1)