#createdby @cat_me_if_you_can2
import asyncio
import requests
import json
from io import BytesIO
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.tl.types import PeerChannel

async def get_gpt_answer(question):
    api_key = udB.get_key("OPENAI_API")
    if not api_key:
        LOGS.error("OpenAI API key not found!")
        return "OpenAI API key not found!"

    url = "https://api.openai.com/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    data = {
        "model": "gpt-4o-mini",
        "messages": [
            {"role": "system", "content": "You specialize in drawing conclusions in detail. Please respond to the query in a friendly tone in Hindi (Hinglish) language. Explain the conversation, and explain what each person talked about and the overall conclusion. If someone was wrong, point out whose argument was less effective and whose was more insightful. Also, rate their conversation style out of 10 using ⭐ emoji at the end. Format will be (user): 5/10 ⭐. 2nd user: 8/10 ⭐."},
            {"role": "user", "content": question}
        ],
        "max_tokens": 1000,
        "temperature": 0.7
    }

    response = requests.post(url, headers=headers, data=json.dumps(data))
    content_json = response.json()
    return content_json["choices"][0]["message"]["content"]

@ultroid_cmd(pattern="conclusion(?: (\d+)|$)")
async def bhai_gpt(e):
    num_messages = int(e.pattern_match.group(1) or 5)
    query = await get_recent_messages(e, num_messages)
    if not query:
        return await e.eor("Not enough messages found in the group.")

    moi = await e.eor(f"🐣")
    try:
        response = await get_gpt_answer(query)
    except Exception as exc:
        LOGS.warning(exc, exc_info=True)
        return await moi.edit(f"Error: \n> {exc}")
    else:
        if len(response) < 4095:
            answer = f"<b></b>\n <i>{response}</i>"
            return await moi.edit(answer, parse_mode="html")
        with BytesIO(response.encode()) as file:
            file.name = "gpt_response.txt"
            await e.client.send_file(
                e.chat_id, file, caption=f"{query[:1020]}", reply_to=e.reply_to_msg_id
            )
        await moi.delete()

async def get_recent_messages(e, num_messages):
    try:
        group = await e.get_chat()
        history = await e.client(GetHistoryRequest(
            peer=group,
            offset_id=0,
            offset_date=None,
            add_offset=0,
            limit=num_messages + 1,  # Fetch messages + 1 to skip the most recent one
            max_id=0,
            min_id=0,
            hash=0
        ))

        if history.messages and len(history.messages) > 1:
            messages = []
            for msg in history.messages[1:]:  # Skip the most recent message
                sender = await e.client.get_entity(msg.from_id) if msg.from_id else None
                sender_name = sender.first_name if sender else "Unknown"
                messages.append(f"{sender_name}: {msg.message}")
            return "\n".join(reversed(messages))  # Reverse the list to maintain the correct order
        else:
            return None
            
    except Exception as exc:
        LOGS.warning(exc, exc_info=True)
        return None