"""
Subplaylist processor for handling subplaylist queue entries.
"""

import threading
import time
import logging
from .constants import AUTO_EXTRACTOR_CHECK_INTERVAL, UI_UPDATE_DELAY, PLAYBACK_STATUS_CHECK_INTERVAL


class SubplaylistProcessor:
    """Manages subplaylist processing from the queue."""
    
    def __init__(self, app):
        self.app = app
        self.processing = False
        
    def start_processor(self):
        """Start the subplaylist processor in a background thread."""
        threading.Thread(target=self._processor_thread, daemon=True).start()

    def _processor_thread(self):
        """Background thread that processes subplaylist queue entries."""
        while True:
            time.sleep(AUTO_EXTRACTOR_CHECK_INTERVAL)
            
            # Only run if app is idle (not recording or playing)
            if self.app.status_var.get() == 'Idle' and not self.app.recording and not self.processing:
                try:
                    self.app.status_var.set('Checking subplaylist queue...')
                    entry = self._get_next_subplaylist_entry()
                    
                    if entry:
                        self.processing = True
                        self.app.status_var.set(f'Processing subplaylist: {entry.get("subplaylist_name", "Unknown")}')
                        logging.info(f'Subplaylist processor: Processing entry {entry.get("id")} - {entry.get("subplaylist_name")}')
                        self._process_subplaylist_entry(entry)
                        self.processing = False
                        
                    # Set status back to Idle if not playing or recording and no entry waiting
                    elif self.app.status_var.get() != 'Playing' and not self.app.recording:
                        self.app.status_var.set('Idle')
                        
                except Exception as e:
                    logging.error(f'Subplaylist processor error: {e}')
                    self.processing = False
                    if self.app.status_var.get() != 'Playing' and not self.app.recording:
                        self.app.status_var.set('Idle')

    def _get_next_subplaylist_entry(self):
        """Get the next subplaylist entry from the queue."""
        try:
            from mysql.mysql_client import get_subplaylist_queue_entries
            entries = get_subplaylist_queue_entries(limit=1)
            return entries[0] if entries else None
        except Exception as e:
            logging.error(f"Error getting next subplaylist entry: {e}")
            return None

    def _process_subplaylist_entry(self, entry):
        """Process a subplaylist queue entry."""
        upload_id = entry.get('id')
        subplaylist_id = entry.get('subplaylist_id')
        playlist_id = entry.get('playlist_id')
        subplaylist_name = entry.get('subplaylist_name', f"ID_{subplaylist_id}")
        
        if not subplaylist_id:
            logging.error(f"Subplaylist entry {upload_id} missing subplaylist_id")
            self._mark_entry_processed(upload_id, error_message="Missing subplaylist_id")
            return
            
        try:
            # Store current context
            current_playlist_name = self.app.selected_playlist.get()
            current_data_row = getattr(self.app, 'current_data_row', 0)
            current_variable_data = getattr(self.app, 'variable_input_data', None)
            
            # Execute subplaylist
            self.app.status_var.set(f'Executing subplaylist: {subplaylist_name}')
            success = self._execute_subplaylist_by_id(subplaylist_id)
            
            # Restore context
            self.app.selected_playlist.set(current_playlist_name)
            self.app.current_data_row = current_data_row
            self.app.variable_input_data = current_variable_data
            
            if success:
                logging.info(f"Subplaylist {subplaylist_name} completed successfully")
                self.app.status_var.set(f'Subplaylist completed: {subplaylist_name}')
                self._mark_entry_processed(upload_id)
            else:
                logging.error(f"Subplaylist {subplaylist_name} execution failed")
                self.app.status_var.set(f'Subplaylist failed: {subplaylist_name}')
                self._mark_entry_processed(upload_id, error_message="Subplaylist execution failed")
            
        except Exception as e:
            logging.error(f"Error processing subplaylist entry {upload_id}: {e}")
            self.app.status_var.set(f'Error processing subplaylist: {e}')
            self._mark_entry_processed(upload_id, error_message=str(e))

    def _execute_subplaylist_by_id(self, subplaylist_id):
        """Execute a subplaylist by ID."""
        try:
            from mysql.mysql_client import get_playlist_actions, get_playlist_by_id
            
            # Get subplaylist info
            subplaylist = get_playlist_by_id(subplaylist_id)
            if not subplaylist:
                logging.error(f"Subplaylist ID {subplaylist_id} not found")
                return False
            
            # Get actions for subplaylist
            actions = get_playlist_actions(subplaylist_id)
            if not actions:
                logging.warning(f"No actions found for subplaylist ID {subplaylist_id}")
                return True  # Consider this successful if no actions
            
            # Execute subplaylist actions
            self._execute_actions_sequence(actions)
            return True
            
        except Exception as e:
            logging.error(f"Error executing subplaylist by ID {subplaylist_id}: {e}")
            return False

    def _execute_actions_sequence(self, actions):
        """Execute a sequence of actions without full playlist context."""
        prev_time = 0
        
        for idx, act in enumerate(actions):
            # Check if playback should stop
            if self.app.status_var.get() != 'Playing' and self.app.status_var.get() != 'Executing subplaylist':
                break
                
            # Wait for timing interval
            interval = max(act.get('timestamp', 0) - prev_time, 0)
            wait_capped = min(interval, 5.0)  # Max 5 second wait
            wait_for = max(0.1, wait_capped)  # Min 0.1 second wait
            
            if wait_for > 0:
                time.sleep(wait_for)
            
            # Execute action
            if act.get('action_type') == 'click':
                self._execute_click(act)
            elif act.get('action_type') in ('key_press', 'key_release'):
                self._execute_key_action(act)
            elif act.get('action_type') == 'screenshot':
                self._execute_screenshot_action()
            elif act.get('action_type') == 'subplaylist':
                # Handle nested subplaylists by creating new queue entries
                self._handle_nested_subplaylist(act)
            elif act.get('action_type') == 'analyze_docs':
                try:
                    self._execute_analyze_docs_action()
                except Exception:
                    logging.exception("analyze_docs action failed in subplaylist")
            elif act.get('action_type') == 'support_docs':
                try:
                    # Delegate to playback-like method for consistency
                    from .playback import PlaybackManager
                    _mgr = PlaybackManager(self.app)
                    _mgr._execute_support_docs_action()
                except Exception:
                    logging.exception("support_docs action failed in subplaylist")
            elif act.get('action_type') == 'search':
                try:
                    self._execute_search_action(act)
                except Exception:
                    logging.exception("search action failed in subplaylist")
            
            prev_time = act.get('timestamp', 0)

    def _handle_nested_subplaylist(self, action):
        """Handle nested subplaylist by creating a new queue entry."""
        subplaylist_id = action.get('subplaylist_id')
        if subplaylist_id:
            from mysql.mysql_client import create_subplaylist_queue_entry
            create_subplaylist_queue_entry(
                playlist_id=getattr(self.app, 'current_playlist_id', None),
                subplaylist_id=subplaylist_id,
                playlist_name=getattr(self.app, 'current_playlist_name', 'Unknown'),
                application_id=getattr(self.app, 'application_id', None),
                user_id=getattr(self.app, 'user_id', None),
                company_id=getattr(self.app, 'company_id', None)
            )
            logging.info(f"Created nested subplaylist queue entry for ID {subplaylist_id}")

    def _execute_click(self, action):
        """Execute a click action."""
        try:
            import pyautogui
            x = action.get('x', 0)
            y = action.get('y', 0)
            # Hide the main Tk app if available while performing the click
            restore = None
            try:
                if getattr(self, 'app', None) is not None and hasattr(self.app, 'withdraw'):
                    try:
                        self.app.attributes('-topmost', False)
                    except Exception:
                        pass
                    try:
                        self.app.withdraw()
                    except Exception:
                        pass
                    def _restore():
                        try:
                            self.app.deiconify()
                            self.app.attributes('-topmost', True)
                        except Exception:
                            pass
                    restore = _restore
            except Exception:
                restore = None
            pyautogui.click(x, y)
            if restore:
                try:
                    restore()
                except Exception:
                    pass
            logging.debug(f"Executed click at ({x}, {y})")
        except Exception as e:
            logging.error(f"Click execution failed: {e}")

    def _execute_key_action(self, action):
        """Execute a key action."""
        try:
            import pyautogui
            key_name = action.get('key_name', '')
            action_type = action.get('action_type', '')
            
            if action_type == 'key_press':
                pyautogui.keyDown(key_name)
            elif action_type == 'key_release':
                pyautogui.keyUp(key_name)
            
            logging.debug(f"Executed {action_type} for key {key_name}")
        except Exception as e:
            logging.error(f"Key action execution failed: {e}")

    def _execute_screenshot_action(self):
        """Execute a screenshot action."""
        try:
            from .screenshot import ScreenshotManager
            screenshot_manager = ScreenshotManager(self.app)
            screenshot_manager.capture_screenshot()
            logging.debug("Executed screenshot action")
        except Exception as e:
            logging.error(f"Screenshot action execution failed: {e}")

    def _execute_analyze_docs_action(self):
        """Execute an analyze docs action."""
        try:
            from .actions import execute_analyze_docs_action
        except Exception:
            logging.error("Analyze docs action not available")
            return
        def _stop():
            return False
        def _set_status(text):
            try:
                self.app.status_var.set(text)
            except Exception:
                pass
        try:
            execute_analyze_docs_action(self.app, stop_requested=_stop, set_status=_set_status)
            logging.debug("Executed analyze docs action")
        except Exception as e:
            logging.error(f"Analyze docs action execution failed: {e}")

    def _execute_search_action(self, action):
        """Execute a search action."""
        try:
            from .openai_analyzer import OpenAIAnalyzer
            analyzer = OpenAIAnalyzer(self.app)
            search_text = action.get('payload', '')
            if search_text:
                analyzer.search_and_click(search_text)
            logging.debug(f"Executed search action for: {search_text}")
        except Exception as e:
            logging.error(f"Search action execution failed: {e}")

    def _mark_entry_processed(self, upload_id, error_message=None):
        """Mark a subplaylist entry as processed."""
        try:
            from mysql.mysql_client import mark_subplaylist_queue_processed
            mark_subplaylist_queue_processed(upload_id, error_message=error_message)
        except Exception as e:
            logging.error(f"Error marking subplaylist entry as processed: {e}")

    def check_queue_once(self):
        """Check subplaylist queue once manually."""
        try:
            entry = self._get_next_subplaylist_entry()
            if entry:
                self.app.status_var.set(f'Subplaylist ready: {entry.get("subplaylist_name", "Unknown")}')
                logging.info(f'Subplaylist queue check: Entry available - {entry.get("subplaylist_name")} (ID: {entry.get("id")})')
            else:
                self.app.status_var.set('No subplaylist entries in queue')
                logging.info('Subplaylist queue check: No entries available')
        except Exception as e:
            logging.error(f"Error checking subplaylist queue: {e}")
            self.app.status_var.set('Error checking subplaylist queue')
