#
# 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 semeion.interfaces.qdrant.qdrant_client import QdrantInterface
from PySide6.QtCore import QObject, Signal, Slot, QThread

class QdrantWorker(QObject):
    result = Signal(object)
    error = Signal(str)
    status = Signal(str)

    def __init__(self):
        super().__init__()
        self.client = None
        
    @Slot()
    def initialize(self):
        self.client = QdrantInterface()
        self.status.emit("Qdrant: ready")

    @Slot()
    def get_collections(self):
        try:
            if self.client is None:
                self.error.emit("Qdrant: Failed to establish connection to QDrant")
                return
            self.status.emit("Qdrant: fetching collections")
            collections = self.client.get_collections()
            self.status.emit("Qdrant: Successfully fetched collections")
            self.result.emit(collections)
        except Exception as e:
            self.error.emit(str(e))


# Service = manages Worker + QThread, UI connects to this
class QdrantService(QObject):
    query_finished = Signal(object)
    query_error = Signal(str)
    query_status = Signal(str)

    _do_discover = Signal()
    
    def __init__(self):
        super().__init__()
        self._thread = QThread()
        self.worker =QdrantWorker()
        
        self.worker.moveToThread(self._thread)
        
        self._thread.started.connect(self.worker.initialize)
        
        self._do_discover.connect(self.worker.get_collections)
        
        self.worker.result.connect(self.query_finished.emit)
        self.worker.error.connect(self.query_error.emit)  
        self.worker.status.connect(self.query_status.emit)
           
        self._thread.start()
        
    @Slot()
    def discover_collections(self):
        self._do_discover.emit()