import sys
import os
import threading
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QTextEdit, QLineEdit, QPushButton,
    QVBoxLayout, QWidget
)
from PyQt5.QtGui import QPixmap, QPainter
from PyQt5.QtCore import Qt, QThread, pyqtSignal

# === 工具函数：获取资源路径（兼容 PyInstaller 打包）===
def resource_path(relative_path):
    """获取资源文件的绝对路径，兼容开发环境和 PyInstaller 打包后的环境"""
    try:
        # PyInstaller 创建临时文件夹 _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

# === 音频支持：启动音效 + 提示音 ===
try:
    import pygame
    pygame.mixer.pre_init(frequency=22050, size=-16, channels=2, buffer=512)
    pygame.mixer.init()
    HAS_AUDIO = True
except Exception as e:
    print(f"[WARN] pygame 初始化失败，所有音效将被禁用: {e}")
    HAS_AUDIO = False


def play_startup_sound():
    """播放本地启动音效 moonshot_startup.mp3"""
    if not HAS_AUDIO:
        return

    try:
        sound_path = resource_path("moonshot_startup.mp3")
        if not os.path.exists(sound_path):
            print(f"[WARN] 启动音效文件未找到: {sound_path}")
            return

        sound = pygame.mixer.Sound(sound_path)
        sound.play()
        pygame.time.wait(int(sound.get_length() * 1000))
    except Exception as e:
        print(f"[ERROR] 播放启动音效失败: {e}")


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

    def __init__(self, user_message):
        super().__init__()
        self.user_message = user_message

    def run(self):
        try:
            url = "https://api.moonshot.cn/v1/chat/completions"
            headers = {
                "Authorization": "Bearer sk-20QS1kOxsgqzNruDNXdmXtta3zEysw4DKd7pSAN2Vf9n8XGg",
                "Content-Type": "application/json"
            }
            data = {
                "model": "moonshot-v1-32k",
                "messages": [
                    {"role": "user", "content": self.user_message}
                ],
                "temperature": 0.7
            }
            import requests
            response = requests.post(url, headers=headers, json=data, timeout=30)
            if response.status_code == 200:
                result = response.json()
                reply = result['choices'][0]['message']['content']
                self.response_received.emit(reply.strip())
            else:
                self.error_occurred.emit(f"API错误: {response.status_code}")
        except Exception as e:
            self.error_occurred.emit(f"请求失败: {str(e)}")


class ChatWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("moonshotAI聊天助手")
        self.setFixedSize(392, 559)
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        self.setStyleSheet("background-color: white; border: 1px solid #ccc;")

        close_btn = QPushButton("×")
        close_btn.setStyleSheet("""
            QPushButton {
                background: red;
                color: white;
                border: none;
                padding: 2px 6px;
                font-size: 12px;
                border-radius: 2px;
                min-width: 20px;
            }
            QPushButton:hover {
                background: darkred;
            }
        """)
        close_btn.clicked.connect(self.close)

        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)
        self.chat_display.setStyleSheet("""
            QTextEdit {
                background-color: #fafafa;
                border: none;
                padding: 10px;
                font-family: Microsoft YaHei;
                font-size: 14px;
                color: #333;
            }
        """)

        self.input_box = QLineEdit()
        self.input_box.setPlaceholderText("请输入消息...")
        self.input_box.returnPressed.connect(self.send_message)
        self.input_box.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                font-size: 14px;
                border: 1px solid #aaa;
                border-radius: 3px;
            }
        """)

        self.send_button = QPushButton("发送")
        self.send_button.clicked.connect(self.send_message)
        self.send_button.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 3px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)

        layout = QVBoxLayout()
        layout.addWidget(close_btn, alignment=Qt.AlignRight)
        layout.addWidget(self.chat_display)
        layout.addWidget(self.input_box)
        layout.addWidget(self.send_button)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

        self.current_worker = None
        self.chat_display.setHtml("欢迎使用 <b>moonshotAI聊天助手</b>！<br><br>请输入消息开始对话...")

    def append_message(self, sender, message):
        self.chat_display.append(f"<b>{sender}:</b> {message}")
        self.chat_display.moveCursor(self.chat_display.textCursor().End)

    def send_message(self):
        user_text = self.input_box.text().strip()
        if not user_text:
            return
        self.append_message("我", user_text)
        self.input_box.clear()
        self.send_button.setEnabled(False)
        self.input_box.setEnabled(False)

        self.current_worker = ChatWorker(user_text)
        self.current_worker.response_received.connect(self.on_response)
        self.current_worker.error_occurred.connect(self.on_error)
        self.current_worker.finished.connect(self.on_finished)
        self.current_worker.start()

    def on_response(self, reply):
        self.append_message("moonshotAI", reply)
        # 播放本地 notify.mp3 提示音
        try:
            if HAS_AUDIO:
                notify_path = resource_path("notify.mp3")
                if os.path.exists(notify_path):
                    sound = pygame.mixer.Sound(notify_path)
                    sound.play()
                else:
                    print(f"[WARN] notify.mp3 未找到: {notify_path}")
        except Exception as e:
            print(f"[WARN] 播放提示音失败: {e}")

    def on_error(self, error_msg):
        self.append_message("系统", f"❌ {error_msg}")

    def on_finished(self):
        self.send_button.setEnabled(True)
        self.input_box.setEnabled(True)
        self.input_box.setFocus()
        self.current_worker = None


class FloatingIcon(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowFlags(
            Qt.FramelessWindowHint |
            Qt.Tool |
            Qt.WindowStaysOnTopHint
        )
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setFixedSize(48, 48)

        self.icon_pixmap = self._load_icon()
        self.chat_window = None
        self.drag_position = None

        screen = QApplication.primaryScreen().availableGeometry()
        x = screen.width() - 60
        y = 20
        self.move(x, y)
        self.show()

    def _load_icon(self):
        icon_path = resource_path("moonshot_icon.png")
        if os.path.exists(icon_path):
            pixmap = QPixmap(icon_path)
            return pixmap.scaled(48, 48, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        else:
            print(f"[WARN] 图标文件未找到: {icon_path}")
            # 使用纯色 fallback
            fallback = QPixmap(48, 48)
            fallback.fill(Qt.transparent)
            return fallback

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.drawPixmap(0, 0, self.icon_pixmap)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drag_position = event.globalPos() - self.frameGeometry().topLeft()

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton and self.drag_position is not None:
            new_pos = event.globalPos() - self.drag_position
            screen = QApplication.primaryScreen().availableGeometry()
            x = max(0, min(new_pos.x(), screen.width() - self.width()))
            y = max(0, min(new_pos.y(), screen.height() - self.height()))
            self.move(x, y)

    def mouseReleaseEvent(self, event):
        self.drag_position = None

    def mouseDoubleClickEvent(self, event):
        if self.chat_window is None:
            self.chat_window = ChatWindow()
            pos = self.pos()
            self.chat_window.move(pos.x() - 392, pos.y())
            self.chat_window.show()
        else:
            if self.chat_window.isVisible():
                self.chat_window.hide()
            else:
                self.chat_window.show()
                self.chat_window.raise_()
                self.chat_window.activateWindow()


def main():
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)

    # 播放启动音效
    sound_thread = threading.Thread(target=play_startup_sound, daemon=True)
    sound_thread.start()

    floating_icon = FloatingIcon()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()