import telegram
from telegram import Update
from telegram import Chat
from threading import Thread
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
import sched, time
import requests
from datetime import datetime


TOKEN = '8096167537:AAEGmjy7ut1n-zsxP5K1dfvokvW6_74-Kbw'


async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # Get basic info of the incoming message
    message_type: str = update.message.chat.type
    text: str = update.message.text
    print(text)
    x = time.time()
    y = datetime.timestamp(update.message.date)

    print(f'User ({update.message.from_user.username}) in {message_type}: "{text}" time in "{y}" now in "{x}"')
    if update.message.from_user.username != "mio_deepseek_bot":
        url = f'http://localhost:3001/api/v1/workspace/teosoftware/chat'
        headers = {"Content-Type": "application/json; charset=utf-8","Authorization": "Bearer 1QE64ZJ-YKD4BT1-G63MCJE-FXEN33V"}
        sendingText = text
        #sendingText = "Ini adalah soalan yang ditanyakan oleh pelanggan kepada anda:"+ text + ". Sila jawab dalam bahasa yang digunakan oleh pelanggan. Jika anda tidak pasti, sila jawab dalam bahasa Melayu."
        data = {
            "message": text,
            "mode": "chat",
            "sessionId": "identifier-to-partition-chats-by-external-id",
        }
        response = requests.post(url, headers=headers, json=data)
        theResponse = response.json()
        if "<think>" in theResponse["textResponse"]:
            send_to_telegram(theResponse["textResponse"].replace("<think>", "").split("</think>",1)[1] ,update.message.chat.id)
        else:
            send_to_telegram(theResponse["textResponse"] ,update.message.chat.id)


    #response = ollama.chat(
    #    model="deepseek-r1:latest",
    #    messages=[
    #        {"role": "user", "content": text},
    #    ],
    #)
    #responseText = response["message"]["content"]
    #send_to_telegram(responseText.replace("<think>", "").split("</think>",1)[1] ,update.message.chat.id)

def send_to_telegram(message,chatID):
    #apiToken = '6101401477:AAHquG04Se0DEmCorkB9-tn8q5EdBikvmfY'
    apiURL = f'https://api.telegram.org/bot{TOKEN}/sendMessage'
    try:
        response = requests.post(apiURL, json={'chat_id': chatID, 'text': message})
        print(response.content)
    except Exception as e:
        print(e)

# Lets us use the /start command
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('Hello there! I\'m a bot. What\'s up?')


# Lets us use the /help command
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('Try typing anything and I will do my best to respond!')


# Lets us use the /custom command
async def custom_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('This is a custom command, you can add whatever text you want here.')

# Log errors
async def error(update: Update, context: ContextTypes.DEFAULT_TYPE):
    print(f'Update {update} caused error {context.error}')


if __name__ == '__main__':
    print("程式運行中")
    app = Application.builder().token(TOKEN).build()
    app.add_handler(CommandHandler('start', start_command))
    app.add_handler(CommandHandler('help', help_command))
    app.add_handler(CommandHandler('custom', custom_command))
    app.add_handler(MessageHandler(filters.TEXT, handle_message))
    app.add_error_handler(error)
    t1 = Thread(target=app.run_polling(poll_interval=3))
    t1.start()