#
# Copyright (c) 2025, mstoeck3
# All rights reserved.
#
# This source code is licensed under the BSD-3-Clause license found in the
# LICENSE file in the root directory of this source tree.
#
from PySide6.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QLabel, QPushButton, QLineEdit, QMenu, QHBoxLayout
from PySide6.QtCore import Qt, Signal
from . import styling
from semeion.services import LLMService, QdrantService, DatabaseService, AppSettings


class MainWindow(QMainWindow):
    main_exec_start = Signal(str)
    
    def __init__(self):
        super().__init__()
        self.db = DatabaseService()
        self.settings = AppSettings()
        print("MAIN: CREATING SERVICES")
        self.create_services()
        print("MAIN: INITIALIZING GUI")
        self.create_ui()
        self.connect_ui_elements()

        
    def create_ui(self):
        self.setWindowTitle("Semeion Interface")
        self.setGeometry(100, 100, 800, 600)
        self.setStyleSheet(styling.main_window_style)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        self.main_layout = QVBoxLayout()
        central_widget.setLayout(self.main_layout)
        
        # Toolbar
        self.create_menuBar()
        
        self.conn_status_layout = QHBoxLayout()
        conn_widget_qdrant = QLabel("Qdrant Interface available")
        conn_widget_llm = QLabel("LLM Interface available")
        conn_widget_embeddings = QLabel("EMB_PLACEHOLDER")
        status_widgets = []
        status_widgets.append(conn_widget_qdrant)
        status_widgets.append(conn_widget_llm)
        status_widgets.append(conn_widget_embeddings)
        for w in status_widgets:
            w.setStyleSheet(styling.status_widget_style)
            self.conn_status_layout.addWidget(w)
        self.main_layout.addLayout(self.conn_status_layout)
        
        
        # spacing
        self.main_layout.addStretch(1)
        
        # branding
        self.brandingLabel = QLabel("S E M E I O N\n")
        self.brandingLabel.setStyleSheet("font-size: 32px; font-weight: bold; font-family: Cantarell;")
        self.main_layout.addWidget(self.brandingLabel, alignment=Qt.AlignmentFlag.AlignCenter)
        
        # search Input       
        self.searchInput = QLineEdit()
        self.searchInput.setPlaceholderText("Natural Language Search...")
        self.searchInput.setFixedWidth(400)
        self.searchInput.setMinimumHeight(30)
        self.searchInput.setStyleSheet(styling.input_style)
        self.main_layout.addWidget(self.searchInput, alignment=Qt.AlignmentFlag.AlignCenter)
        self.main_layout.addSpacing(10)
        
        self.executeButton = QPushButton("Execute")
        self.executeButton.setAttribute(Qt.WidgetAttribute.WA_Hover)
        self.executeButton.setStyleSheet(styling.button_style)
        self.main_layout.addWidget(self.executeButton, alignment=Qt.AlignmentFlag.AlignCenter)
        
        self.main_layout.addStretch(1)
        
    def create_menuBar(self):
        menuBar = self.menuBar()
        action_caseManager = menuBar.addAction("&Case Manager", self.open_case_manager)
        action_caseManager.setStatusTip("Manage Cases")
        action_ingestionManager = menuBar.addAction("&Ingestion Manager", self.open_ingestion_manager)
        action_ingestionManager.setStatusTip("Ingest various Artifacts into dataset")
        menuBar_settingsMenu = QMenu("&Settings", self)
        action_connectionManager = menuBar_settingsMenu.addAction("&Manage Server Connections", self.open_connection_manager)
        menuBar.addMenu(menuBar_settingsMenu)
        menuBar_settingsMenu.setStatusTip("Application Settings")
        menuBar_about = QMenu("&About", self)
        action_aboutModal = menuBar_about.addAction("&About...", self.open_about_window)
        menuBar.addMenu(menuBar_about)
        menuBar.setStyleSheet(styling.toolbar_style)
        
    def create_services(self):
        self.llm_service = LLMService()
        self.qdrant_service = QdrantService()
        
        # Button -> executes LLM Service
        self.main_exec_start.connect(self.llm_service.query)
        # response handling
        self.llm_service.query_finished.connect(self.handle_llm_response)
        
        # connect qdrant signals
        self.qdrant_service.query_finished.connect(self.handle_qdrant_response)
        # Qdrant: execute collection discovery on startup
        self.qdrant_service.discover_collections()
        
    def connect_ui_elements(self):
        self.searchInput.returnPressed.connect(self.execute_from_input)
        self.executeButton.clicked.connect(self.execute_from_input)
        
    def execute_from_input(self) -> str|None:
        query = self.searchInput.text().strip()
        if not query:
            return 
        self.main_exec_start.emit(query)
        self.executeButton.setDisabled(True)
        self.searchInput.setDisabled(True)
        self.reenable_list = [self.executeButton, self.searchInput]
        print("MAIN: LLM QUERY SUBMIT:", query)
        
    def handle_llm_response(self, response):
        self.enable_input(self.reenable_list)
        print("MAIN: LLM RESPONSE:", response)

    def handle_qdrant_response(self, response):
        print("MAIN: QDRANT COLLECTIONS:", response)
        
    def enable_input(self, elements: list):
        for e in elements:
          e.setEnabled(True)  
        
    def open_case_manager(self):
        print("clicked case manager")
        
    def open_ingestion_manager(self):
        print("clicked ingestion manager")
        
    def open_connection_manager(self):
        print("clicked open connection manager")
        
    def open_about_window(self):
        print("clicked open about")
        