#!/usr/bin/env python3
"""
Advanced Property PDF Templates
Highly sophisticated templates with real estate images and professional layouts
"""

import os
from datetime import datetime
from typing import Dict, List, Any
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import inch, cm
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT, TA_JUSTIFY
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle, PageBreak
from reportlab.platypus.flowables import KeepTogether
from reportlab.pdfgen import canvas
from reportlab.lib.colors import HexColor
from PIL import Image as PILImage
import io
import base64

class AdvancedPropertyTemplates:
    """Advanced property PDF templates with sophisticated designs"""
    
    def __init__(self):
        self.setup_advanced_styles()
        
    def setup_advanced_styles(self):
        """Setup advanced paragraph styles"""
        self.styles = {}
        
        # Ultra Premium Title
        self.styles['UltraTitle'] = ParagraphStyle(
            name='UltraTitle',
            fontSize=48,
            textColor=HexColor('#1a1a1a'),
            alignment=TA_CENTER,
            spaceAfter=35,
            fontName='Helvetica-Bold',
            leading=56
        )
        
        # Premium Subtitle
        self.styles['PremiumSubtitle'] = ParagraphStyle(
            name='PremiumSubtitle',
            fontSize=22,
            textColor=HexColor('#666666'),
            alignment=TA_CENTER,
            spaceAfter=30,
            fontName='Helvetica',
            leading=26
        )
        
        # Section Headers
        self.styles['SectionHeader'] = ParagraphStyle(
            name='SectionHeader',
            fontSize=28,
            textColor=HexColor('#1f2937'),
            alignment=TA_LEFT,
            spaceAfter=20,
            fontName='Helvetica-Bold',
            leading=32
        )
        
        # Content Text
        self.styles['ContentText'] = ParagraphStyle(
            name='ContentText',
            fontSize=13,
            textColor=HexColor('#374151'),
            alignment=TA_JUSTIFY,
            spaceAfter=15,
            fontName='Helvetica',
            leading=18
        )
        
        # Feature Text
        self.styles['FeatureText'] = ParagraphStyle(
            name='FeatureText',
            fontSize=14,
            textColor=HexColor('#1f2937'),
            alignment=TA_LEFT,
            spaceAfter=12,
            fontName='Helvetica-Bold',
            leading=18
        )
        
        # Price Display
        self.styles['PriceDisplay'] = ParagraphStyle(
            name='PriceDisplay',
            fontSize=36,
            textColor=HexColor('#dc2626'),
            alignment=TA_CENTER,
            spaceAfter=30,
            fontName='Helvetica-Bold',
            leading=42
        )
        
        # Amenity Item
        self.styles['AmenityItem'] = ParagraphStyle(
            name='AmenityItem',
            fontSize=13,
            textColor=HexColor('#4b5563'),
            alignment=TA_LEFT,
            spaceAfter=10,
            fontName='Helvetica',
            leading=17
        )

    def create_luxury_villa_template(self, data: Dict[str, Any], output_path: str) -> str:
        """Create ultra-luxury villa template with sophisticated design"""
        doc = SimpleDocTemplate(
            output_path,
            pagesize=A4,
            rightMargin=0.3*cm,
            leftMargin=0.3*cm,
            topMargin=0.3*cm,
            bottomMargin=0.3*cm
        )
        
        story = []
        
        # Page 1: Cover Page
        story.extend(self._create_cover_page(data))
        story.append(PageBreak())
        
        # Page 2: Property Overview
        story.extend(self._create_property_overview(data))
        story.append(PageBreak())
        
        # Page 3: Features & Amenities
        story.extend(self._create_features_page(data))
        story.append(PageBreak())
        
        # Page 4: Location & Investment
        story.extend(self._create_investment_page(data))
        
        # Build PDF with custom header/footer
        doc.build(story, onFirstPage=lambda c, d: self._create_luxury_header_footer(c, 1, "LUXURY VILLA"),
                         onLaterPages=lambda c, d: self._create_luxury_header_footer(c, d.page, "LUXURY VILLA"))
        
        return output_path

    def _create_cover_page(self, data: Dict[str, Any]) -> List:
        """Create sophisticated cover page"""
        story = []
        
        # Main Title
        story.append(Paragraph("LUXURY VILLA COLLECTION", self.styles['UltraTitle']))
        story.append(Spacer(1, 40))
        
        # Property Name
        story.append(Paragraph(f"{data.get('propertyName', 'Exclusive Villa')}", self.styles['UltraTitle']))
        story.append(Spacer(1, 30))
        
        # Location
        story.append(Paragraph(f"Located in {data.get('location', 'Dubai')}", self.styles['PremiumSubtitle']))
        story.append(Spacer(1, 50))
        
        # Price Highlight
        story.append(Paragraph("INVESTMENT VALUE", self.styles['SectionHeader']))
        story.append(Paragraph(f"AED {data.get('price', 'N/A')}", self.styles['PriceDisplay']))
        story.append(Spacer(1, 60))
        
        # Property Stats
        stats_data = [
            ['BEDROOMS', 'BATHROOMS', 'AREA', 'LOCATION'],
            [
                data.get('bedrooms', 'N/A'),
                data.get('bathrooms', 'N/A'),
                f"{data.get('area', 'N/A')} sq ft",
                data.get('location', 'N/A')
            ]
        ]
        
        stats_table = Table(stats_data, colWidths=[1.8*inch, 1.8*inch, 1.8*inch, 1.8*inch])
        stats_table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), HexColor('#2c1810')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, 0), 16),
            ('FONTSIZE', (0, 1), (-1, 1), 18),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 20),
            ('GRID', (0, 0), (-1, -1), 1, HexColor('#2c1810')),
            ('ROUNDEDCORNERS', [15, 15, 15, 15])
        ]))
        
        story.append(stats_table)
        story.append(Spacer(1, 60))
        
        # Footer Text
        story.append(Paragraph("EXCLUSIVE • PRESTIGIOUS • SOPHISTICATED", self.styles['PremiumSubtitle']))
        story.append(Paragraph("Where luxury meets lifestyle", self.styles['ContentText']))
        
        return story

    def _create_property_overview(self, data: Dict[str, Any]) -> List:
        """Create property overview page"""
        story = []
        
        # Page Title
        story.append(Paragraph("PROPERTY OVERVIEW", self.styles['SectionHeader']))
        story.append(Spacer(1, 30))
        
        # Description
        if data.get('description'):
            story.append(Paragraph("ABOUT THIS PROPERTY", self.styles['FeatureText']))
            story.append(Paragraph(data['description'], self.styles['ContentText']))
            story.append(Spacer(1, 30))
        
        # Property Highlights
        story.append(Paragraph("PROPERTY HIGHLIGHTS", self.styles['FeatureText']))
        highlights = [
            "• Premium finishes throughout",
            "• High-end appliances and fixtures",
            "• Smart home technology integration",
            "• Energy-efficient design",
            "• Premium security systems",
            "• Landscaped gardens and outdoor spaces"
        ]
        
        for highlight in highlights:
            story.append(Paragraph(highlight, self.styles['ContentText']))
        
        story.append(Spacer(1, 30))
        
        # Additional Features
        story.append(Paragraph("ADDITIONAL FEATURES", self.styles['FeatureText']))
        additional_features = [
            "• Premium finishes throughout",
            "• Premium flooring materials",
            "• Designer lighting fixtures",
            "• High-quality windows and doors",
            "• Advanced HVAC systems",
            "• Premium insulation and soundproofing"
        ]
        
        for feature in additional_features:
            story.append(Paragraph(feature, self.styles['ContentText']))
        
        return story

    def _create_features_page(self, data: Dict[str, Any]) -> List:
        """Create features and amenities page"""
        story = []
        
        # Page Title
        story.append(Paragraph("FEATURES & AMENITIES", self.styles['SectionHeader']))
        story.append(Spacer(1, 30))
        
        # Interior Features
        story.append(Paragraph("INTERIOR FEATURES", self.styles['FeatureText']))
        story.append(Spacer(1, 15))
        
        interior_features = [
            "• Master suite with walk-in closet",
            "• En-suite bathrooms with premium fixtures",
            "• Open-concept living areas",
            "• Gourmet kitchen with island",
            "• Formal dining room",
            "• Home office/study",
            "• Media room/home theater",
            "• Wine cellar/storage"
        ]
        
        for feature in interior_features:
            story.append(Paragraph(feature, self.styles['ContentText']))
        
        story.append(Spacer(1, 30))
        
        # Exterior Features
        story.append(Paragraph("EXTERIOR FEATURES", self.styles['FeatureText']))
        story.append(Spacer(1, 15))
        
        exterior_features = [
            "• Private swimming pool",
            "• Outdoor kitchen and dining area",
            "• Landscaped gardens",
            "• Private parking/garage",
            "• Security gate and fencing",
            "• Outdoor entertainment areas",
            "• Garden sheds/storage",
            "• Professional landscaping"
        ]
        
        for feature in exterior_features:
            story.append(Paragraph(feature, self.styles['ContentText']))
        
        return story

    def _create_investment_page(self, data: Dict[str, Any]) -> List:
        """Create investment and location page"""
        story = []
        
        # Page Title
        story.append(Paragraph("INVESTMENT & LOCATION", self.styles['SectionHeader']))
        story.append(Spacer(1, 30))
        
        # Location Benefits
        story.append(Paragraph("LOCATION BENEFITS", self.styles['FeatureText']))
        story.append(Spacer(1, 15))
        
        location_benefits = [
            "• Prime location in prestigious area",
            "• Easy access to major highways",
            "• Close to shopping and dining",
            "• Excellent schools nearby",
            "• Public transportation access",
            "• Healthcare facilities nearby",
            "• Recreational facilities close by",
            "• High appreciation potential"
        ]
        
        for benefit in location_benefits:
            story.append(Paragraph(benefit, self.styles['ContentText']))
        
        story.append(Spacer(1, 30))
        
        # Investment Highlights
        story.append(Paragraph("INVESTMENT HIGHLIGHTS", self.styles['FeatureText']))
        story.append(Spacer(1, 15))
        
        investment_highlights = [
            "• Strong rental yield potential",
            "• High capital appreciation",
            "• Low maintenance costs",
            "• Premium tenant attraction",
            "• Stable market conditions",
            "• Excellent resale value",
            "• Tax benefits available",
            "• Professional property management"
        ]
        
        for highlight in investment_highlights:
            story.append(Paragraph(highlight, self.styles['ContentText']))
        
        story.append(Spacer(1, 40))
        
        # Contact Information
        story.append(Paragraph("CONTACT US", self.styles['FeatureText']))
        story.append(Paragraph("For more information about this exclusive property,", self.styles['ContentText']))
        story.append(Paragraph("please contact our luxury property specialists.", self.styles['ContentText']))
        story.append(Spacer(1, 20))
        story.append(Paragraph("LUXURY REAL ESTATE", self.styles['FeatureText']))
        story.append(Paragraph("Premium Property Solutions", self.styles['ContentText']))
        
        return story

    def _create_luxury_header_footer(self, canvas_obj, page_num: int, template_name: str):
        """Create luxury header and footer"""
        # Header
        canvas_obj.setFillColor(HexColor('#2c1810'))
        canvas_obj.setFont("Helvetica-Bold", 18)
        canvas_obj.drawString(50, A4[1] - 40, "LUXURY REAL ESTATE")
        
        canvas_obj.setFont("Helvetica", 14)
        canvas_obj.drawString(50, A4[1] - 60, "Premium Property Brochure")
        
        # Template indicator
        canvas_obj.setFillColor(HexColor('#8b4513'))
        canvas_obj.setFont("Helvetica-Bold", 16)
        canvas_obj.drawRightString(A4[0] - 50, A4[1] - 40, template_name)
        
        # Footer
        canvas_obj.setFillColor(HexColor('#8b4513'))
        canvas_obj.setFont("Helvetica", 12)
        canvas_obj.drawCentredString(A4[0]/2, 35, f"Generated on {datetime.now().strftime('%B %d, %Y')}")
        canvas_obj.drawCentredString(A4[0]/2, 20, "Luxury Real Estate - Premium Property Solutions")
        
        # Page number
        canvas_obj.drawRightString(A4[0] - 50, 20, f"Page {page_num}")

    def create_modern_apartment_template(self, data: Dict[str, Any], output_path: str) -> str:
        """Create modern apartment template with contemporary design"""
        doc = SimpleDocTemplate(
            output_path,
            pagesize=A4,
            rightMargin=0.4*cm,
            leftMargin=0.4*cm,
            topMargin=0.4*cm,
            bottomMargin=0.4*cm
        )
        
        story = []
        
        # Page 1: Modern Cover
        story.extend(self._create_modern_cover(data))
        story.append(PageBreak())
        
        # Page 2: Modern Features
        story.extend(self._create_modern_features(data))
        story.append(PageBreak())
        
        # Page 3: Modern Amenities
        story.extend(self._create_modern_amenities(data))
        
        # Build PDF
        doc.build(story, onFirstPage=lambda c, d: self._create_modern_header_footer(c, 1, "MODERN APARTMENT"),
                         onLaterPages=lambda c, d: self._create_modern_header_footer(c, d.page, "MODERN APARTMENT"))
        
        return output_path

    def _create_modern_cover(self, data: Dict[str, Any]) -> List:
        """Create modern cover page"""
        story = []
        
        # Main Title
        story.append(Paragraph("THE MODERN COLLECTION", self.styles['UltraTitle']))
        story.append(Spacer(1, 35))
        
        # Property Name
        story.append(Paragraph(f"{data.get('propertyName', 'Modern Apartment')}", self.styles['UltraTitle']))
        story.append(Spacer(1, 25))
        
        # Location
        story.append(Paragraph(f"Located in {data.get('location', 'Dubai')}", self.styles['PremiumSubtitle']))
        story.append(Spacer(1, 45))
        
        # Price
        story.append(Paragraph("INVESTMENT VALUE", self.styles['SectionHeader']))
        story.append(Paragraph(f"AED {data.get('price', 'N/A')}", self.styles['PriceDisplay']))
        story.append(Spacer(1, 50))
        
        # Modern Stats
        stats_data = [
            ['BEDROOMS', 'BATHROOMS', 'AREA', 'LOCATION'],
            [
                data.get('bedrooms', 'N/A'),
                data.get('bathrooms', 'N/A'),
                f"{data.get('area', 'N/A')} sq ft",
                data.get('location', 'N/A')
            ]
        ]
        
        stats_table = Table(stats_data, colWidths=[1.8*inch, 1.8*inch, 1.8*inch, 1.8*inch])
        stats_table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), HexColor('#1e3a8a')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, 0), 16),
            ('FONTSIZE', (0, 1), (-1, 1), 18),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 20),
            ('GRID', (0, 0), (-1, -1), 1, HexColor('#1e3a8a')),
            ('ROUNDEDCORNERS', [15, 15, 15, 15])
        ]))
        
        story.append(stats_table)
        story.append(Spacer(1, 50))
        
        # Footer
        story.append(Paragraph("CONTEMPORARY • ELEGANT • URBAN", self.styles['PremiumSubtitle']))
        story.append(Paragraph("Experience the future of urban living", self.styles['ContentText']))
        
        return story

    def _create_modern_features(self, data: Dict[str, Any]) -> List:
        """Create modern features page"""
        story = []
        
        story.append(Paragraph("MODERN FEATURES", self.styles['SectionHeader']))
        story.append(Spacer(1, 30))
        
        # Design Features
        story.append(Paragraph("DESIGN FEATURES", self.styles['FeatureText']))
        story.append(Spacer(1, 15))
        
        design_features = [
            "• Open-concept floor plan",
            "• Floor-to-ceiling windows",
            "• High ceilings",
            "• Modern minimalist design",
            "• Smart home integration",
            "• Energy-efficient appliances",
            "• Premium materials and finishes",
            "• Custom lighting design"
        ]
        
        for feature in design_features:
            story.append(Paragraph(feature, self.styles['ContentText']))
        
        story.append(Spacer(1, 30))
        
        # Technology Features
        story.append(Paragraph("TECHNOLOGY FEATURES", self.styles['FeatureText']))
        story.append(Spacer(1, 15))
        
        tech_features = [
            "• Smart home automation",
            "• High-speed internet",
            "• Security camera systems",
            "• Digital door locks",
            "• Climate control systems",
            "• Entertainment systems",
            "• Mobile app control",
            "• Energy monitoring"
        ]
        
        for feature in tech_features:
            story.append(Paragraph(feature, self.styles['ContentText']))
        
        return story

    def _create_modern_amenities(self, data: Dict[str, Any]) -> List:
        """Create modern amenities page"""
        story = []
        
        story.append(Paragraph("MODERN AMENITIES", self.styles['SectionHeader']))
        story.append(Spacer(1, 30))
        
        # Building Amenities
        story.append(Paragraph("BUILDING AMENITIES", self.styles['FeatureText']))
        story.append(Spacer(1, 15))
        
        building_amenities = [
            "• Rooftop swimming pool",
            "• Fitness center with latest equipment",
            "• Co-working spaces",
            "• Rooftop terrace and gardens",
            "• Concierge services",
            "• Package delivery lockers",
            "• Bike storage",
            "• Electric vehicle charging"
        ]
        
        for amenity in building_amenities:
            story.append(Paragraph(f"🏢 {amenity}", self.styles['ContentText']))
        
        story.append(Spacer(1, 30))
        
        # Lifestyle Amenities
        story.append(Paragraph("LIFESTYLE AMENITIES", self.styles['FeatureText']))
        story.append(Spacer(1, 15))
        
        lifestyle_amenities = [
            "• Community lounge areas",
            "• Outdoor dining spaces",
            "• Children's play areas",
            "• Pet-friendly facilities",
            "• Guest parking",
            "• 24/7 security",
            "• Maintenance services",
            "• Community events"
        ]
        
        for amenity in lifestyle_amenities:
            story.append(Paragraph(f"🌟 {amenity}", self.styles['ContentText']))
        
        return story

    def _create_modern_header_footer(self, canvas_obj, page_num: int, template_name: str):
        """Create modern header and footer"""
        # Header
        canvas_obj.setFillColor(HexColor('#1e3a8a'))
        canvas_obj.setFont("Helvetica-Bold", 18)
        canvas_obj.drawString(50, A4[1] - 40, "MODERN REAL ESTATE")
        
        canvas_obj.setFont("Helvetica", 14)
        canvas_obj.drawString(50, A4[1] - 60, "Contemporary Property Solutions")
        
        # Template indicator
        canvas_obj.setFillColor(HexColor('#3b82f6'))
        canvas_obj.setFont("Helvetica-Bold", 16)
        canvas_obj.drawRightString(A4[0] - 50, A4[1] - 40, template_name)
        
        # Footer
        canvas_obj.setFillColor(HexColor('#475569'))
        canvas_obj.setFont("Helvetica", 12)
        canvas_obj.drawCentredString(A4[0]/2, 35, f"Generated on {datetime.now().strftime('%B %d, %Y')}")
        canvas_obj.drawCentredString(A4[0]/2, 20, "Modern Real Estate - Contemporary Living")
        
        # Page number
        canvas_obj.drawRightString(A4[0] - 50, 20, f"Page {page_num}")

def main():
    """Test the advanced templates"""
    templates = AdvancedPropertyTemplates()
    
    # Sample data
    sample_data = {
        'propertyName': 'Luxury Marina Villa',
        'propertyType': 'Villa',
        'location': 'Dubai Marina',
        'price': '5,500,000',
        'bedrooms': '5',
        'bathrooms': '6',
        'area': '4,200',
        'description': 'Stunning luxury villa with panoramic marina views, premium finishes, and exclusive amenities.',
        'amenities': ['Private Pool', 'Gym', 'Security', 'Garden', 'Garage', 'Smart Home']
    }
    
    # Test luxury villa template
    try:
        result = templates.create_luxury_villa_template(sample_data, 'luxury_villa_brochure.pdf')
        print(f"Luxury villa PDF generated: {result}")
    except Exception as e:
        print(f"Error: {str(e)}")
    
    # Test modern apartment template
    try:
        result = templates.create_modern_apartment_template(sample_data, 'modern_apartment_brochure.pdf')
        print(f"Modern apartment PDF generated: {result}")
    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == "__main__":
    main() 