import json
import os
import mysql.connector
from google.auth.exceptions import DefaultCredentialsError
from google.oauth2 import service_account
import vertexai
from vertexai.generative_models import GenerativeModel, Part, SafetySetting, FinishReason
import vertexai.generative_models as generative_models
import sys


def humam(prompt_2):
    key_path = "/var/www/html/smart-hub/public/futurefous-b541452ac5cf.json"
    try:
        credentials = service_account.Credentials.from_service_account_file(
            key_path,
            scopes=["https://www.googleapis.com/auth/cloud-platform"]
        )
        vertexai.init(project="futurefous", location="europe-west1", credentials=credentials)
        
        model = GenerativeModel("gemini-1.5-flash-002")
        
    	# prompt = "text": f"{text}"
        # full_prompt = ' '.join(prompt_2) + 
        generation_config = {
            "max_output_tokens": 1000,
            "temperature": 0,
            "top_p": 0.95,
        }
        safety_settings = [
            SafetySetting(
                category=SafetySetting.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
                threshold=SafetySetting.HarmBlockThreshold.BLOCK_ONLY_HIGH
            ),
            SafetySetting(
                category=SafetySetting.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
                threshold=SafetySetting.HarmBlockThreshold.BLOCK_ONLY_HIGH
            ),
            SafetySetting(
                category=SafetySetting.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
                threshold=SafetySetting.HarmBlockThreshold.BLOCK_ONLY_HIGH
            ),
            SafetySetting(
                category=SafetySetting.HarmCategory.HARM_CATEGORY_HARASSMENT,
                threshold=SafetySetting.HarmBlockThreshold.BLOCK_ONLY_HIGH
            ),
        ]
        response = model.generate_content(
            prompt_2,
            generation_config=generation_config,
            safety_settings=safety_settings,
        )
        return response.text
    except Exception as e:
        return f"An error occurred during humanization: {str(e)}"


if __name__ == "__main__":
    if len(sys.argv) > 2:
        text = sys.argv[1]
        question = sys.argv[2]
        answer = text.replace('\\"', '')

        #print(answer)
        prompt = f"""
---------		
Guidelines:
---------		
        1.	Character Limit Handling:
        
		•	If the input {answer} value exceeds 2000 tokens, truncate the response to include only the first 2000 tokens and append the following message only {answer} value exceeds 4000 tokens:
		
		“The result is too large to display here. If you need the full details, please provide additional filters such as UPC, User Id, or Ticket Id to refine the response.” 
		
		2. Don't mention (truncated due to length exceeding 2000 tokens) in Input.
---------		
		
        Optimize the response and give within 4 seconds

Specific and Direct: Avoid overly broad or complex requests.

Example: Instead of "Analyze user trends," write "Provide the top 3 user trends by region in the last month."
Limit Output: Ask for fewer items or shorter results.

Example: "Summarize in 2 sentences" instead of "Provide a detailed analysis."
Use Clear Context: Provide essential details upfront to reduce ambiguity.

Example: "Using data from October, show top regions by sales."
Avoid Extra Complexity: Break down tasks into smaller, manageable steps if possible.


if{answer} is empty check {question} and give response based on that .
 print any if or else don't combine both.
        If the question is related to any help/any guidance/guide/assistance/what can you do/what can you do for me they ask --- return "I’m here to help you with support tickets and OTL forms. Whether you need details about users, tickets/inbox/mail, or anything else, I’ve got your back to make sure things run smoothly—so you can focus on what matters most."
         else If the question is related to what is otl/what is ticket --- return "OTL is One time Link.There are 4 type of OTL Forms.Account Closure,Content Mapping,Revenue Share,Youtube OAc.
        Tickets are whether the users send any request related to their problem or request to add information about them."
         else if the question is related to tell me your name like that -- return "I'm Assistly AI."
         else if the question is related to gm/good morning like that -- return "Hello! How can I assist you today?"
     return only what i mention don't add anything else.
       else
        Don't use the word database or db .
        Don't display User question.only need answers.
        Don't show , included in the summary as requested.
        don't tell me as requested excluded.
        It could be display as human text not as requested it shows.
      Highlight the most important or notable data points by bolding the text
     Use simple language and avoid technical jargon.
     Short description is enough.
     Forms closed by Admins or staffs.
     in this don't use the wors sql or database or query, just convert to human readable text.
**based on {question} get {answer} from it,just convert to human readable text**
**Don't show table name**
don't display like this "[COUNT(*):1]" , display count:1 like that
don't display tag_id and it's value in human text, display others.
in {answer} omit the tag_id and it's value.
in {answer} omit the action_id and it's value.

don't display like this
There are no tickets with tag ID 23 that are not completed,
display like
There are no unresolved takedown requests.

**in {question} they ask ticket id, display it. and use ticket# instead of ID**

 Convert the following database result into a human-readable answer to the user question. User question: '{question}'. Database result: {answer}. Highlight the most important or notable data points by bolding the text, Use standard bullet points (•) instead of asterisks or other symbols, Remove the asterisks from the response, Ensure ALL data points are displayed, especially if a specific number (e.g., top 10) was requested., Your summary should be informative, giving a complete overview of all the counts and names in the data, along with light contextual information to make the data more meaningful., Remove underscores from terms like 'unique_listener' or 'yt_network_abuse' to create a more human-friendly format., Correct the typo in the user’s question and then respond accordingly
        """
        full_prompt = ' '.join(answer) + prompt

        humam = humam(full_prompt)
        print(humam)
        # prompt_2 = """
        #     You are an AI that converts numeric financial data into human-readable text.

        #     The output must be concise, professional, and easy to understand.
        # """
        # prompt_2 = """
        #         To clarify if the release status "Pending Moderation" is associated with UPC 5057302837990, the following question could be phrased for a query:

        #         "Does the release status 'Pending Moderation' correspond to the UPC 5057302837990?"

        #         Let me know if you'd like to proceed with this!
        # """
        # prompt_2 = f"""
        #     Question_1: is the upc 5057302837990 has pending moderation?
        #     Answer_1: say yes/no

        #     Question_2: how is the existing share distribution split for this upc 5054316798316?
        #     Answer_2: say percentage value e.g. 50%

        #     database result get json read Humanise text answer change also 
        #11. If the user input contains **greetings** (such as "hello," "hi," "good morning"), respond with a humanized greeting with more polite and gentle like: "Hi, Please provide the data you would like me to summarize. I'm ready to help! 😊".

        # """  
        
#         prompt_2 = f"""Given the following data, please provide a human-friendly summary of the information:

# {question}

# Please follow these guidelines:
# 1. Start with a brief overview sentence summarizing the main insight from the data.
# 2. Present ALL the count-name pairs from the data, using a bulleted list for clarity. Do not omit any data points.
# 3. If the data includes country codes, convert them to full country names.
# 4. **Highlight the most important or notable data points by bolding the text**.
# 5. If applicable, mention any notable trends or patterns in a single sentence after the list.
# 6. Use simple language and avoid technical jargon.
# 7. Use standard bullet points (•) instead of asterisks or other symbols.
# 8. Ensure ALL data points are displayed, especially if a specific number (e.g., top 10) was requested.
# 9. Your summary should be informative, giving a complete overview of all the counts and names in the data, along with light contextual information to make the data more meaningful.
# 10. If the input is **entertainment-related** (like asking about movies, news or cricket scores) or contains unrelated questions (like jokes), return the following fallback content: "I'm sorry, as Luna AI Analyst at RouteNote, I can only assist you providing data on tracks and streams. I can offer detailed insights, analytics, and performance metrics related to this. How can I help you today?"
# 11. If the user includes words like "thanks" or mentions pricing, respond with a welcoming message, such as: "Feel free to ask!"
# 12. Remove underscores from terms like "unique_listener" to create a more human-friendly format.
# 13. If the user input contains the word **Nodataavailable** (such as "Nodataavailable"), respond with a humanized greeting with more polite and gentle like: "It looks like there's no data available for your request regarding '{question}'. Feel free to ask about something else, and I'll be happy to assist!"



# If the data set is large (more than 20 items), you may group similar items or use sub-bullets to organize the information more clearly, but do not omit any data points."""



        
    else:
        print("Please provide input text as command-line arguments.")
            # Question : check release_status for upc ?
            # Answer: The release status for the product with UPC 5057302837990 is "Your Action Needed." This means that further action is required before the release can proceed.




 