from transformers import pipeline

from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain.llms import OpenAI

from load_model import call_palm
from calling_apis import google_api_key, openai_api_key

class meta_content_generation:
    
    """
    Class meta_content_generation:
    Provides methods to generate content for social media platforms using Language Models (LLMs) and prompt templates.
    """
        


    def facebook_ads_gen(self, product_name:str, product_description:str, tone_of_voice:str, targeted_audience="", plans_promotions="", language='En', model_name='Google Palm 2', creativity='Original')->str:
        
        """
        Generates a Facebook ad based on the provided product details and parameters.

        Parameters:
            - product_name (str): Name of the product for the ad.
            - product_description (str): Description of the product for the ad.
            - tone_of_voice (str): Tone of the ad.
            - targeted_audience (str): Target audience for the ad (optional).
            - plans_promotions (str): Plans and promotions for the ad (optional).

        Returns:
            - Generated Facebook ad text.
        """

        temp = 0

        if creativity == 'Original':
            temp = 0
        elif creativity == 'Balanced':
            temp = 0.25
        elif creativity == 'Creative':
            temp = 0.5
        elif creativity == 'Spirited':
            temp = 0.75
        elif creativity == 'Visionary':
            temp = 1


        if model_name == 'Google Palm 2':
            llm = call_palm(google_api_key, temperature=temp)

        elif model_name == 'GPT-3.5':
            llm = OpenAI(model_name='gpt-3.5-turbo', openai_api_key=openai_api_key, temperature=temp)

        elif model_name == 'GPT-4':
            llm = OpenAI(model_name='gpt-4', openai_api_key=openai_api_key, temperature=temp)


        
        if language == 'En':
            
            if targeted_audience != "" and plans_promotions != "":
                facebook_ads_prompt = f"Generate a Facebook ad for {product_name} Product. {product_name} is {product_description}. Our Target Audience is {targeted_audience}. Our plans and promotions is {plans_promotions}. Tone of the ad should be {tone_of_voice}"

            elif targeted_audience == "" and plans_promotions != "":
                facebook_ads_prompt = f"Generate a Facebook ad for {product_name} Product. {product_name} is {product_description}. Our plans and promotions is {plans_promotions}. Tone of the ad should be {tone_of_voice}"

            elif targeted_audience != "" and plans_promotions == "":
                facebook_ads_prompt = f"Generate a Facebook ad for {product_name} Product. {product_name} is {product_description}. Our Target Audience is {targeted_audience}. Tone of the ad should be{tone_of_voice}."

            else:
                facebook_ads_prompt = f"Generate a Facebook ad for {product_name} Product. {product_name} is {product_description}. Tone of the ad Should be {tone_of_voice}."
        
        elif language == 'Ar':
            
            if targeted_audience != "" and plans_promotions != "":
                facebook_ads_prompt = f"انشئ إعلانًا على فيسبوك لمنتج {product_name}. {product_name} هو {product_description}. جمهورنا المستهدف هو {targeted_audience}. خططنا وعروضنا هي {plans_promotions}. يجب أن يكون توجه الإعلان {tone_of_voice}."

            elif targeted_audience == "" and plans_promotions != "":
                facebook_ads_prompt = f"قم بإنشاء إعلان على فيسبوك لـ {product_name} المنتج. {product_name} هو {product_description}. خططنا وعروضنا هي {plans_promotions}. يجب أن يكون تون الإعلان {tone_of_voice}"

            elif targeted_audience != "" and plans_promotions == "":
                facebook_ads_prompt = f"أنشئ إعلانًا على فيسبوك لمنتج {product_name}. {product_name} هو {product_description}. جمهورنا المستهدف هو {targeted_audience}. يجب أن يكون طابع الإعلان {tone_of_voice}"

            else:
                facebook_ads_prompt = f"انشئ إعلانًا على فيسبوك لـ {product_name} المنتج. {product_name} هو {product_description}. يجب أن يكون نبرة الإعلان {tone_of_voice}."

                
        facebook_ads_promptTemp = PromptTemplate(
        input_variables=["text_input"],
        template="You are a Professional Facebook Ad Copywriter:\n{text_input}\nFacebook Ad:")
    
        facebook_ad_extraction_chain = LLMChain(llm=llm, prompt=facebook_ads_promptTemp)
        facebook_ad = facebook_ad_extraction_chain.run(facebook_ads_prompt)
        
        return facebook_ad
    
    def facbook_camp_gen(self, product_name:str, product_desc:str, days:int, goal:str, language='En', model_name='Google Palm 2', creativity='Original') -> str:
        
         """
        Generates a Facebook Campign based on the provided product details and goals.

        Parameters:
            - product_name (str): Name of the product for the ad.
            - product_desc (str): Description of the product for the ad.
            - days (int): Number of campaign days.
            - goal (str): Goal of the campaign.
            - language (str): the language of the generated content (optional, default value is 'EN').

        Returns:
            - Facebook_ad (str): Generated Facebook Campaign .
        """
         temp = 0

         if creativity == 'Original':
            temp = 0
         elif creativity == 'Balanced':
            temp = 0.25
         elif creativity == 'Creative':
            temp = 0.5
         elif creativity == 'Spirited':
            temp = 0.75
         elif creativity == 'Visionary':
            temp = 1


         if model_name == 'Google Palm 2':
            llm = call_palm(google_api_key, temperature=temp)

         elif model_name == 'GPT-3.5':
            llm = OpenAI(model_name='gpt-3.5-turbo', openai_api_key=openai_api_key, temperature=temp)

         elif model_name == 'GPT-4':
            llm = OpenAI(model_name='gpt-4', openai_api_key=openai_api_key, temperature=temp)


         if language == 'En':
            
            facebook_ads_prompt = f"Generate a {days} days Persuative Facebook campaign (don't mention any budget) calendar for our {product_name}. {product_name} is {product_desc}. with the goal to {goal}."
            facebook_ads_promptTemp = PromptTemplate(
            input_variables=["text_input"],
            template="""You are a Professional Facebook Digital Marketer:\n{text_input}\nFacebook Campaign:""")
        
         elif language == 'Ar':
            
            facebook_ads_prompt = f"قم بإنشاء حملة فايسبوك قائمة لمدة {days} يومًا (دون الإشارة إلى أي ميزانية) لـ {product_name} الخاص بنا. {product_name} هو {product_desc}. بهدف {goal}."
            facebook_ads_promptTemp = PromptTemplate(
            input_variables=["text_input"],
            template="أنت مسوّق رقمي محترف على فيسبوك:\n{text_input}\nحملة فيسبوك:")
        
         facebook_ad_extraction_chain = LLMChain(llm=llm, prompt=facebook_ads_promptTemp)
         facebook_ad = facebook_ad_extraction_chain.run(facebook_ads_prompt)
        
         return facebook_ad

    def facebook_post_gen(self, tone_of_voice:str, topic:str, language='En', model_name='Google Palm 2', creativity='Original') -> str:
        
        """
        Generates a Facebook Post based on the provided topic.

        Parameters:
            - tone_of_voice (str): The tone of the facebook post.
            - topic (str): The facebook post topic
            - language (str): the language of the generated content (optional, default value is 'EN').

        Returns:
            - Facebook_post (str): Generated Facebook Post .
        """
        
        temp = 0

        if creativity == 'Original':
            temp = 0
        elif creativity == 'Balanced':
            temp = 0.25
        elif creativity == 'Creative':
            temp = 0.5
        elif creativity == 'Spirited':
            temp = 0.75
        elif creativity == 'Visionary':
            temp = 1


        if model_name == 'Google Palm 2':
            llm = call_palm(google_api_key, temperature=temp)

        elif model_name == 'GPT-3.5':
            llm = OpenAI(model_name='gpt-3.5-turbo', openai_api_key=openai_api_key, temperature=temp)

        elif model_name == 'GPT-4':
            llm = OpenAI(model_name='gpt-4', openai_api_key=openai_api_key, temperature=temp)


        if language == 'En':
            
            productDesc_prompt = f"Generate an attractive and persuasive facebook post on {topic}. Tone should be {tone_of_voice}. Post dosen't include any photos or videos."
            productDesc_promptTemp = PromptTemplate(
            input_variables=["text_input"],
            template="You are a professional facebook content creator:\n{text_input}\n\nFacebook Post:")
    
        
        elif language == 'Ar':
            
            productDesc_prompt = f"انشر منشورًا جذابًا ومقنعًا على فيسبوك حول {topic}. يجب أن يكون النبرة {tone_of_voice}. لا يتضمن المنشور أي صور أو مقاطع فيديو."
            productDesc_promptTemp = PromptTemplate(
            input_variables=["text_input"],
            template="أنت مبدع محترف في إنشاء محتوى على فيسبوك:\n{text_input}\n\nمنشور فيسبوك:")

        productDesc_extraction_chain = LLMChain(llm=llm, prompt=productDesc_promptTemp)
        product_desc = productDesc_extraction_chain.run(productDesc_prompt)
        
        return product_desc

    def img2text(self, url:str) -> str:
        
         """
        Function to extract text from an image using a pre-trained image captioning model.

        Parameters:
            self: The instance of a class (if this function is part of a class).
            url (str): The URL pointing to the image for which text extraction is required.

        Returns:
            out (str): The extracted text from the provided image.
        """
            
         image_to_text = pipeline("image-to-text", model='Salesforce/blip-image-captioning-base')

         text = image_to_text(url)

         out = text[0]['generated_text']
        
         return out


    def generate_InstaCap(self, scenario:str, tone_of_voice:str, form:str, language='En', model_name='Google Palm 2', creativity='Original') -> str:
        
        """
        Generates a Instagram Caption based on the image description.

        Parameters:
            - tone_of_voice (str): The tone of the facebook post.
            - scenario (str): The description of the image
            - form (str): the form of the caption (short - long) forms

        Returns:
            - instaCap (str): Generated Image Caption.
        """
        
        temp = 0

        if creativity == 'Original':
            temp = 0
        elif creativity == 'Balanced':
            temp = 0.25
        elif creativity == 'Creative':
            temp = 0.5
        elif creativity == 'Spirited':
            temp = 0.75
        elif creativity == 'Visionary':
            temp = 1


        if model_name == 'Google Palm 2':
            llm = call_palm(google_api_key, temperature=temp)

        elif model_name == 'GPT-3.5':
            llm = OpenAI(model_name='gpt-3.5-turbo', openai_api_key=openai_api_key, temperature=temp)

        elif model_name == 'GPT-4':
            llm = OpenAI(model_name='gpt-4', openai_api_key=openai_api_key, temperature=temp)


        if language == 'En':
            
            instaCap_prompt = f"Craft a {form} Caption on my Instagram Image Here is the description of my Instagram Image: {scenario}.\nThe tone should be {tone_of_voice}"
            instaCap_promptTemp = PromptTemplate(
            input_variables=["text_input"],
            template="You are infulencer:\n{text_input}\nInstagram Caption:")
        
        elif language == 'Ar':
            
            instaCap_prompt = f"صياغة توضيح {form} على صورة إنستغرام الخاصة بي. إليك وصف صورة إنستغرامي: {scenario}.يجب أن يكون التون {tone_of_voice}."
            instaCap_promptTemp = PromptTemplate(
            input_variables=["text_input"],
            template="أنت مؤثر: \n{text_input}\n وصف بوست الانستغرام:")
            
        instaCap_extraction_chain = LLMChain(llm=llm, prompt=instaCap_promptTemp)
        instaCap = instaCap_extraction_chain.run(instaCap_prompt)
        
        return instaCap