# # openai_helper.py
# import os
# import json
# import logging
# import requests
# from db_config import get_db_connection
# from dotenv import load_dotenv

# load_dotenv()

# OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')

# def send_openai_analysis(call_id):
#     conn = get_db_connection()
#     cursor = conn.cursor()
    
#     cursor.execute("SELECT * FROM 6840_sarvamresponse WHERE callid = %s AND status = 1", (call_id,))
#     calls = cursor.fetchall()

#     for call in calls:
#         transcript = call[2]  # Assuming 'transcript' is at index 2
#         prompt = f"""
#         Analyze the following customer call transcript and return the following in JSON format:
#         1. Top 5 Keywords
#         2. Overall Sentiment (Positive, Negative, Neutral)
#         3. Detected Emotions (e.g., Happy, Angry, Frustrated)
#         4. Summary of the Call
#         5. Sales Intent (High, Medium, Low)

#         Transcript:
#         \"{transcript}\"
#         """

#         headers = {
#             "Authorization": f"Bearer {OPENAI_API_KEY}",
#             "Content-Type": "application/json"
#         }

#         body = {
#             "model": "gpt-4",
#             "messages": [
#                 {"role": "system", "content": "You are a helpful assistant that analyzes call center transcripts."},
#                 {"role": "user", "content": prompt}
#             ],
#             "temperature": 0.7
#         }

#         try:
#             response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=body, verify=False)
#             data = response.json()
#             content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
#             parsed = json.loads(content)

#             # Extracted fields
#             keywords = json.dumps(parsed.get("Top 5 Keywords", []))
#             sentiment = parsed.get("Overall Sentiment", "")
#             emotions = json.dumps(parsed.get("Detected Emotions", []))
#             summary = parsed.get("Summary of the Call", "")

#             cursor.execute("""
#                 UPDATE 6840_sarvamresponse SET
#                 status = 2,
#                 keywords = %s,
#                 sentiment = %s,
#                 emotions = %s,
#                 summary = %s,
#                 openai_raw = %s
#                 WHERE id = %s
#             """, (keywords, sentiment, emotions, summary, content, call[0]))  # call[0] = id
#             conn.commit()
#             logging.info(f"✅ OpenAI processed callid {call_id}")

#         except Exception as e:
#             logging.error(f"❌ OpenAI error for callid {call_id}: {str(e)}")

#     cursor.close()
#     conn.close()


# orginal code 
import os
import json
import logging
import boto3
from botocore.exceptions import BotoCoreError, ClientError
from db_config import get_db_connection
from dotenv import load_dotenv
from message_helper import send_message
logging.basicConfig(level=logging.INFO)

load_dotenv()

# AWS Credentials
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID', 'AKIAUWPMKLMSD556YYR5')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY', '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')
AWS_REGION = os.getenv('AWS_REGION', 'eu-north-1')

bedrock = boto3.client(
    service_name='bedrock-runtime',
    region_name=AWS_REGION,
    aws_access_key_id=AWS_ACCESS_KEY_ID,
    aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)

MODEL_ID = "amazon.nova-lite-v1:0"

def send_openai_analysis(call_id, bid=None):
    conn = get_db_connection()
    cursor = conn.cursor()

    # Use dynamic table name if bid is provided, otherwise use default
    if bid:
        sarvam_response_table = f"{bid}_sarvamresponse"
        calls_table = f"{bid}_calls"
    else:
        sarvam_response_table = "7417_sarvamresponse"  # Default fallback
        calls_table = "7417_calls"

    cursor.execute(f"SELECT * FROM {sarvam_response_table} WHERE callid = %s AND status = 1", (call_id,))
    calls = cursor.fetchall()

    for call in calls:
        transcript = call[2]  # transcript is at index 1, not 2
        
        # Debug logging
        logging.info(f"🔍 Retrieved transcript for callid {call_id}: {transcript[:100] if transcript else 'None'}...")
        
        if not transcript or transcript.strip() == "":
            logging.warning(f"⚠️ Empty or null transcript for callid {call_id}")
            continue 
        prompt = f"""
                        Analyze the following customer call transcript and return the following in JSON format:
                        1. Top 5 Keywords
                        2. Overall Sentiment with all (Positive, Negative, Neutral) with percentage 
                        3. Detected Emotions (e.g., Happy, Angry, Frustrated)
                        4. Summary of the Call
                        5. Sales Intent (High, Medium, Low)
                        6. Customer Details (name, phone, email if available)

                        Transcript:
                        \"{transcript}\"  
                    """

        logging.info(f"Sending prompt for callid {call_id}: {prompt}")

        body = {
            "inferenceConfig": {
                "max_new_tokens": 1000,
                "temperature": 0.7,
                "top_p": 0.9
            },
            "messages": [
                {
                    "role": "user",
                    "content":[{"text": prompt}]
                }
            ]
        }

        try:
            logging.info(f"Request body: {json.dumps(body)}")

            response = bedrock.invoke_model(
                modelId=MODEL_ID,
                contentType="application/json",
                accept="application/json",
                body=json.dumps(body)
            )

            raw_response = response['body'].read().decode('utf-8')
            logging.info(f"Raw response body for callid {call_id}: {raw_response}")

            content = ''
            if raw_response:
                response_body = json.loads(raw_response)

                content_list = response_body.get('output', {}).get('message', {}).get('content', [])
                if content_list and isinstance(content_list, list):
                    content = content_list[0].get('text', '').strip()

            if not content:
                logging.error(f"Empty content received for callid {call_id}")
                raise ValueError(f"Empty content received from Bedrock response for callid {call_id}")

            if content.startswith("```json"):
                content = content.replace("```json", "").replace("```", "").strip()
            elif content.startswith("```"):
                content = content.replace("```", "").strip()

            content = content.replace("\n", "").strip()
            logging.info(f"Cleaned response content for callid {call_id}: {content}")
            try:
                parsed = json.loads(content)
            except json.JSONDecodeError as e:
                logging.error(f"JSON decode error for callid {call_id}: {str(e)}")
                logging.error(f"Invalid content: {content}")
                raise

            keywords = json.dumps(parsed.get("Top 5 Keywords", []))
            sentiment = json.dumps(parsed.get("Overall Sentiment", []))
            emotions = json.dumps(parsed.get("Detected Emotions", []))
            summary = parsed.get("Summary of the Call", "")
            salesintent = json.dumps(parsed.get("Sales Intent", []))
            customer_details = json.dumps(parsed.get("Customer Details", {}))

            logging.info(f"Parsed data for callid {call_id}: Keywords: {keywords}, Sentiment: {sentiment}, Emotions: {emotions}, Summary: {summary}, Sales: {salesintent}, Customer: {customer_details}")

            cursor.execute(f"""
                UPDATE {calls_table} SET
                status = 2,
                keywords = %s,
                sentiments = %s,
                emotions = %s,
                summary = %s,
                sand_logic_response = %s,
                sales_intent = %s,
                transcripts = %s,
                customer_details = %s
                WHERE callid = %s
            """, (keywords, sentiment, emotions, summary, content, salesintent, transcript, customer_details, call_id))

            conn.commit()
            send_message(call_id, bid)
            logging.info(f"✅ Bedrock processed callid {call_id}")

        except (BotoCoreError, ClientError, json.JSONDecodeError, ValueError) as e:
            logging.error(f"❌ Bedrock error for callid {call_id}: {str(e)}")
            logging.error(f"⚠️ Failed content: {content if 'content' in locals() else 'No content available'}")

    cursor.close()
    conn.close()









