import base64
import io
import google.generativeai as genai
from PIL import Image
from app.core.config import settings

class GeminiService:
    def __init__(self):
        if not settings.GOOGLE_API_KEY:
            raise ValueError("No GOOGLE_API_KEY set")
        genai.configure(api_key=settings.GOOGLE_API_KEY)
        self.model = genai.GenerativeModel('gemini-2.0-flash')

    def generate_product_description(self, product_name, features, site_name, tone, images_base64=None):
        text_prompt = f"""
        Act as a Senior SEO Specialist and Copywriter for an Iranian e-commerce store named "{site_name}".
        
        Task: Write a high-converting, SEO-optimized product description in Persian (Farsi).
        
        Product Info:
        - Name: {product_name}
        - Key Features Provided: {features}
        - Tone: {tone}
        
        Instructions:
        1. Analyze the provided images (if any) to describe visual details (color, material, design) that are not listed in features.
        2. Focus on User Intent and Benefits (sell the result, not just features).
        3. Include a catchy H2 title.
        4. Use bullet points for readability.
        5. Naturally include LSI keywords related to the product name.
        6. Output Format: Clean HTML (h2, p, ul, li tags). NO ```html wrapper.
        """

        content_parts = [text_prompt]

        if images_base64:
            for img_b64 in images_base64:
                try:
                    image_data = base64.b64decode(img_b64)
                    image = Image.open(io.BytesIO(image_data))
                    content_parts.append(image)
                except Exception as img_err:
                    print(f"Image processing error: {img_err}")
        
        response = self.model.generate_content(content_parts)
        return response.text

gemini_service = GeminiService()
