import os
import random

from environment import Environment
from twilio.rest import Client


class SMSService:
    
    @staticmethod
    def generate_reward_description(credit_type, compensation=None, min_compensation=None, max_compensation=None, hard_cash=False):
        """
        Generates a description of the reward based on the credit amount and type, or a range if boundaries are specified.
            Args:
                compensation (str): The amount of credit to be rewarded.
                credit_type (str): The type of credit to be rewarded.
                min_compensation(int): The minimum boundary for the reward.
                max_compensation(int): The maximum boundary for the reward.
        """

        if hard_cash and credit_type.lower() == "percent":
            raise ValueError("Credit type cannot be 'percent' when hard_cash is True")

        prefix = "$" if credit_type.lower() == "cash" else ""
        suffix = "%" if credit_type.lower() == "percent" else ""
        trailing_word = "" if hard_cash else " off"

        if min_compensation is not None and max_compensation is not None and min_compensation > 0 and max_compensation > 0:
            min_amount = f"{float(min_compensation):.2f}".rstrip("0").rstrip(".")
            max_amount = f"{float(max_compensation):.2f}".rstrip("0").rstrip(".")
            credit_description = f"up to {prefix}{max_amount}{suffix}{trailing_word}"
        else:
            compensation = f"{float(compensation):.2f}".rstrip("0").rstrip(".")
            credit_description = f"{prefix}{compensation}{suffix}{trailing_word}"

        return credit_description
    
    @staticmethod
    def type_of_content(content_type):
        content_type_final = ""

        if content_type == "instagramStory":
            content_type_final = "Instagram Story"
        
        elif content_type == "ugc":
            content_type_final = "photo or video"

        elif content_type == "instagramPost":
            content_type_final = "Instagram Post"

        elif content_type == "instagramReel":
            content_type_final = "Instagram Reel"
        
        elif content_type == "tiktokVideo":
            content_type_final = "Tiktok Video"

        else:
            raise ValueError("Invalid content type")
        
        return content_type_final


    @staticmethod
    def send_sms(target, message):
        suppress_sms = os.getenv("SUPPRESS_SMS") == "true"
        if suppress_sms: # if running tests, don't send any real texts
            return message, None
        
        account_sid = Environment.TWILIO_ACCOUNT_SID
        auth_token = Environment.TWILIO_AUTH_TOKEN
        twilio_number = "+18334867100"
        twilio_client = Client(account_sid, auth_token)
        response = twilio_client.messages.create(
            to=target, from_=twilio_number, body=message
        )
        return message, response
        

    @staticmethod
    def send_welcome_text(target, business_name="StoryIt", business_welcome_text = ""):

        message =  f"""
Welcome to the {business_name} rewards program! You can earn incredible rewards by sharing your Instagram stories and content. 💰💫 Start sharing and unlock cash, credit, discounts, and more! 📸✨ 
""" if business_welcome_text == "" else business_welcome_text

        reply_stop = f"""
        
Reply HELP for help or STOP to unsubscribe.
"""

        complete_message = message + reply_stop

        print(complete_message)

        print("Sending welcome text to " + target)
        try:
            return SMSService.send_sms(target, complete_message)
        except Exception as e:
            print(e)
            return None

    @staticmethod
    def send_offer_acceptance_text(
        target,
        name,
        business_name,
        content_type):

        content_type_final = SMSService.type_of_content(content_type)

        extended_message = ""

        if content_type == "ugc":
            extended_message = "🎉 Your submission is under review. We'll let you know when your reward is ready!"
        
        if content_type == "tiktokVideo":
            extended_message = f"🎉 Now, it's time to post your Tiktok video. Remember to follow all the requirements! 💫📸"

        else:
            extended_message = f"🎉 Now, it's time to post your {content_type_final}. Remember to follow all the requirements and to leave your {content_type_final} up for at least 24 hours! 💫📸"

        message = f"""
Congratulations{', ' + name + ', ' if name else ' '}on accepting the offer from {business_name}! {extended_message}
"""
        print("Sending offer acceptance text to " + target)
        try:
            return SMSService.send_sms(target, message)
        except Exception as e:
            print(e)
            return None

    @staticmethod
    def send_post_approved_text(target, whitelabel_url=None, discount_code=None):
        discount_code_text = f"\nYour discount code is: {discount_code}\n" if discount_code else ""

        message = f"""
Your content was verified. Your well-deserved reward is now available in your wallet. Simply click the link below to access it and start enjoying the benefits! 💰✨

https://{whitelabel_url if whitelabel_url else Environment.WEB_APP_URL}/wallet
{discount_code_text}
Thank you for your participation and stay tuned for more exciting opportunities and rewards in the future. Happy redeeming! 😊🛍️
        """
        print("Sending post approved text to " + target)
        try:
            return SMSService.send_sms(target, message)
        except Exception as e:
            print(e)
            return None

    @staticmethod
    def send_post_rejected_text(target, is_ugc_offer=False):
        message = (
            """
Oops! We encountered a little hiccup in verifying your post. Not to worry, though! To receive your well-deserved reward, please fill out the form below and we will contact you shortly. 

https://forms.gle/ZbZQX7RQ4qG8ZyvG7

If your account is set to private, kindly ensure that one of our verification accounts is following you. We appreciate your cooperation and look forward to resolving this issue promptly. Thank you! 
"""
            if not is_ugc_offer
            else """
We were unable to successfully verify your submission. If you believe this is an error, please fill out the form below and we will contact you shortly.

https://forms.gle/ZbZQX7RQ4qG8ZyvG7
"""
        )
        print("Sending post rejected text to " + target)
        try:
            return SMSService.send_sms(target, message)
        except Exception as e:
            print(e)
            return None

    @staticmethod
    def send_accept_instagram_follow_request_text(target, bot_username):
        message = f"""
🚨 Our verification account, @{bot_username}, has requested to follow you on Instagram.

Please accept the request so we can verify your post/reel! 🚨
"""
        print("Sending accept follow request text to " + target)
        try:
            return SMSService.send_sms(target, message)
        except Exception as e:
            print(e)
            return None

    @staticmethod
    def send_credit_reminder_text(target, business_name, compensation, credit_type, whitelabel_url=None):

        credit_description = SMSService.generate_reward_description(credit_type, compensation)

        messages = [
            f"""
Hi there! This is a friendly reminder that you have {credit_description} at {business_name}.

To access your reward: https://{whitelabel_url if whitelabel_url else Environment.WEB_APP_URL}/wallet
""",
            f"""
Hey! Just a reminder to use your {credit_description} on your next purchase at {business_name}.

https://{whitelabel_url if whitelabel_url else Environment.WEB_APP_URL}/wallet
""",
        ]
        message = random.choice(messages)
        print("Sending credit reminder text to " + target)
        try:
            return SMSService.send_sms(target, message)
        except Exception as e:
            print(e)
            return None

    @staticmethod
    def send_private_offer_alert_text(target, business_name, client_ig_handle, content_type, credit_type, compensation=None, min_compensation=None, max_compensation=None, whitelabel_url=None, hard_cash=False):
        print("Sending private offer alert to " + target)

        credit_description = SMSService.generate_reward_description(credit_type, compensation, min_compensation, max_compensation, hard_cash)

        content_type_formatted = SMSService.type_of_content(content_type)

        article = "an" if content_type_formatted[0].lower() in "aeiou" else "a"

        tag_instruction = "" if content_type == "ugc" else f" and tag @{client_ig_handle}"
        
        url = f"https://{whitelabel_url if whitelabel_url else Environment.WEB_APP_URL}/wallet"

        message = f"""
You have received an exclusive offer from {business_name}! 👀🎉

Upload {article} {content_type_formatted}{tag_instruction} to earn {credit_description}! 📸✨

Check it out: {url}
        """

        try:
            return SMSService.send_sms(target, message)
        except Exception as e:
            print(e)
            return None

    @staticmethod
    def send_post_reminder_text(target, client_ig_handle, content_type, credit_type, compensation=None, min_compensation=None, max_compensation=None, hard_cash=False):
        print("sending post reminder to " + target)
        print(max_compensation)

        credit_description = SMSService.generate_reward_description(credit_type, compensation, min_compensation, max_compensation, hard_cash)

        content_type_formatted = SMSService.type_of_content(content_type)

        article = "an" if content_type_formatted[0].lower() in "aeiou" else "a"

        tag_instruction = "" if content_type == "ugc" else f" and tag @{client_ig_handle}"

        message = f"""
🙈 Oops! We couldn't find your post.

Please make sure to upload {article} {content_type_formatted}{tag_instruction} to unlock your {credit_description}! 📸✨
        """
        
        try:
            print("Sending post reminder text to " + target)
            print(content_type)

            return SMSService.send_sms(target, message)
        except Exception as e:
            print(e)
            return None

    @staticmethod
    def send_post_resubmission(target, missing_requirement_error_code, content_type, client_instagram_handle="", specific_product=""):
        content_type_final = SMSService.type_of_content(content_type)

        missing_requirement = ""

        if (missing_requirement_error_code == "-1"):
            missing_requirement = f"The @{client_instagram_handle} tag was not found"

        elif (missing_requirement_error_code == "-2"):
            missing_requirement = f"A {specific_product} was not found"

        elif (missing_requirement_error_code == "-69"):
            missing_requirement = f"Profanity was detected"

        message = f"""
🔄 Uh oh! It looks like your {content_type_final} needs to be re-uploaded.

{missing_requirement} in your {content_type_final}, give it another go to unlock your reward! 📸✨
        """

        try:
            print("Sending post resubmission text to " + target + ": " +  missing_requirement)
            return SMSService.send_sms(target, message)
        except Exception as e:
            print(e)
            return None