import sys
import json
import requests
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, QWidget, QFrame
from PyQt6.QtCore import Qt, QThread, pyqtSignal
from PyQt6.QtGui import QColor

class ChatWorker(QThread):
    response_received = pyqtSignal(str)
    error_occurred = pyqtSignal(str)

    def __init__(self, message, history):
        super().__init__()
        self.message = message
        self.history = history

    def run(self):
        url = "https://app.wordware.ai/api/released-app/fa2aacfa-8224-413d-8e8a-80a0422de2b8/run"
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ww-HrgCNtPQjYoIAgHkLLljXn7J5dB2yvdoVparU7kgXenC6vQd6Yih16'
        }
        payload = {
            "inputs": {
                "History": self.history,
                "New Message": self.message
            },
            "version": "^1.0"
        }

        try:
            response = requests.post(url, json=payload, headers=headers)
            response.raise_for_status()
            
            full_response = ""
            for line in response.iter_lines():
                if line:
                    data = json.loads(line)
                    if data['type'] == 'chunk' and 'value' in data['value'] and isinstance(data['value']['value'], str):
                        chunk_text = data['value']['value']
                        full_response += chunk_text
                        self.response_received.emit(chunk_text)
            
            if not full_response:
                self.error_occurred.emit("Не удалось получить ответ от сервера.")
        except requests.exceptions.RequestException as e:
            error_message = f"Ошибка запроса: {str(e)}"
            if hasattr(e, 'response') and e.response is not None:
                error_message += f"\nОтвет сервера: {e.response.text}"
            self.error_occurred.emit(error_message)
        except Exception as e:
            self.error_occurred.emit(f"Неизвестная ошибка: {str(e)}")

class ChatWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("ИИ Чат")
        self.setGeometry(100, 100, 800, 600)
        self.setStyleSheet("""
            QMainWindow {
                background-color: #2C3E50;
            }
            QTextEdit, QLineEdit {
                background-color: #34495E;
                color: #ECF0F1;
                border: none;
                border-radius: 10px;
                padding: 10px;
                font-size: 14px;
            }
            QPushButton {
                background-color: #3498DB;
                color: white;
                border: none;
                border-radius: 10px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #2980B9;
            }
            QFrame {
                background-color: #34495E;
                border-radius: 15px;
            }
        """)

        main_frame = QFrame(self)
        self.setCentralWidget(main_frame)

        self.chat_display = QTextEdit(self)
        self.chat_display.setReadOnly(True)
        self.chat_display.setStyleSheet("""
            QTextEdit {
                background-color: #2C3E50;
                border: 1px solid #34495E;
            }
        """)

        self.input_field = QLineEdit(self)
        self.input_field.setPlaceholderText("Введите сообщение...")
        self.send_button = QPushButton("Отправить", self)
        self.clear_button = QPushButton("Очистить чат", self)

        layout = QVBoxLayout(main_frame)
        layout.addWidget(self.chat_display)
        input_layout = QHBoxLayout()
        input_layout.addWidget(self.input_field)
        input_layout.addWidget(self.send_button)
        layout.addLayout(input_layout)
        layout.addWidget(self.clear_button)

        self.send_button.clicked.connect(self.send_message)
        self.input_field.returnPressed.connect(self.send_message)
        self.clear_button.clicked.connect(self.clear_chat)

        self.user_color = QColor("#3498DB")
        self.bot_color = QColor("#2ECC71")
        self.error_color = QColor("#E74C3C")
        self.system_prompt = "Ты - русскоязычный ассистент. Всегда отвечай на русском языке, кратко и по существу."
        self.chat_history = f"{self.system_prompt}\n"

    def send_message(self):
        message = self.input_field.text()
        if message:
            self.append_message("Человек", message, self.user_color)
            self.worker = ChatWorker(message, self.chat_history)
            self.worker.response_received.connect(self.update_chat)
            self.worker.error_occurred.connect(self.show_error)
            self.worker.start()
            self.input_field.clear()

    def update_chat(self, response):
        self.append_message("Ассистент", response, self.bot_color)
        self.chat_history += f"Человек: {self.worker.message}\nАссистент: {response}\n"

    def show_error(self, error_message):
        self.append_message("Ошибка", error_message, self.error_color)

    def append_message(self, sender, message, color):
        self.chat_display.setTextColor(color)
        self.chat_display.append(f"{sender}: {message}")
        self.chat_display.setTextColor(Qt.GlobalColor.white)
        self.chat_display.verticalScrollBar().setValue(self.chat_display.verticalScrollBar().maximum())

    def clear_chat(self):
        self.chat_display.clear()
        self.chat_history = f"{self.system_prompt}\n"

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ChatWindow()
    window.show()
    sys.exit(app.exec())