#!/usr/bin/env python3
"""
Session Worker Thread - vzug-e-hinge
====================================
QThread worker for non-blocking session execution.

This worker runs session.start_session() or session.resume_session()
in a background thread, preventing GUI freezing and enabling 
real-time status updates.

IMPORTANT: Creates thread-local database connection to avoid SQLite
threading errors.

Author: Kynsight
Version: 1.1.0
Date: 2025-11-09
"""

from PyQt6.QtCore import QThread, pyqtSignal
import sqlite3


class SessionWorker(QThread):
    """
    Worker thread for session execution.
    
    Runs session.start_session() or resume_session() in background 
    to prevent GUI blocking. Emits finished signal when session completes.
    
    CRITICAL: Creates a new database connection in the worker thread
    to avoid SQLite's "objects created in a thread can only be used
    in that same thread" error.
    """
    
    # Signals
    finished = pyqtSignal(bool)  # success/failure
    
    def __init__(self, session, db_path, resume_mode=False):
        """
        Initialize worker.
        
        Args:
            session: Session instance to execute
            db_path: Path to database file (for thread-local connection)
            resume_mode: True to resume, False to start (default)
        """
        super().__init__()
        self.session = session
        self.db_path = db_path
        self.resume_mode = resume_mode
    
    def run(self):
        """
        Execute session in background thread.
        
        This method runs in a separate thread, keeping the GUI responsive.
        Creates a thread-local database connection to avoid SQLite errors.
        All session signals (status_changed, command_started, etc.) are
        automatically thread-safe thanks to Qt's signal/slot mechanism.
        """
        try:
            # Create thread-local database connection
            thread_db_conn = sqlite3.connect(self.db_path)
            
            # Replace session's database connection with thread-local one
            old_conn = self.session.db_conn
            self.session.db_conn = thread_db_conn
            
            try:
                if self.resume_mode:
                    # Resume paused session
                    self.session.resume_session()
                    success = True
                else:
                    # Start new session
                    success = self.session.start_session()
                
                # Emit result
                self.finished.emit(success)
                
            finally:
                # Close thread-local connection
                thread_db_conn.close()
                
                # Restore original connection
                self.session.db_conn = old_conn
            
        except Exception as e:
            print(f"[ERROR] Worker exception: {e}")
            self.finished.emit(False)
