import logging
import os
from aiogram import Bot, Dispatcher, executor, types
from gtts import gTTS
import openai

# --- SOZLAMALAR ---
API_TOKEN = '8345994145:AAH6C9YJmgdOdlCRGrzEkpajd92fZ0H2Myg'

# Groq API sozlamalari
openai.api_key = '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' # gsk_... bilan boshlanadi
openai.api_base = "https://api.groq.com/openai/v1" # Groq serveriga yo'naltirish

# Papkalarni tekshirish
if not os.path.exists('temp_voice'):
    os.makedirs('temp_voice')

logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)

SYSTEM_INSTRUCTION = """
Sen Qamashi tumani hokimligi xodimi — "Raqamli ko'makchi"san. 
Vazifang: Fuqarolarga muloyim va rasmiy o'zbek tilida javob berish.
"""

async def generate_voice_and_send(message, text):
    """Matnni audioga aylantirib yuboruvchi yordamchi funksiya"""
    try:
        voice_path = f"temp_voice/v_{message.message_id}_{message.from_user.id}.mp3"
        # O'zbek tili tr orqali o'xshashroq chiqadi
        tts = gTTS(text=text, lang='tr') 
        tts.save(voice_path)

        await message.answer(text)
        with open(voice_path, 'rb') as voice:
            await message.answer_voice(voice)
        
        os.remove(voice_path)
    except Exception as e:
        logging.error(f"TTS Error: {e}")
        await message.answer(text)

@dp.message_handler(commands=['start'])
async def cmd_start(message: types.Message):
    await message.answer("Assalomu alaykum! Qamashi tumani hokimligi botiga xush kelibsiz. Savolingizni yozib qoldiring.")

@dp.message_handler()
async def process_message(message: types.Message):
    try:
        # Groq modelidan foydalanamiz
        response = openai.ChatCompletion.create(
            model="llama-3.3-70b-versatility", # Groq-dagi eng kuchli model
            messages=[
                {"role": "system", "content": SYSTEM_INSTRUCTION},
                {"role": "user", "content": message.text}
            ]
        )
        ai_text = response.choices[0].message.content
        
    except Exception as e:
        logging.error(f"AI Error: {e}")
        ai_text = "Hozirda serverda nosozlik bor. Iltimos, birozdan so'ng qayta urunib ko'ring."

    # Matn va ovozni yuborish
    await generate_voice_and_send(message, ai_text)

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)