"""Background task management"""

import threading
import time
from typing import Dict, Callable, Any


class Task:
    """Task class"""
    def __init__(self, task_name: str, task_func: Callable, *args, **kwargs):
        """Initialize task
        
        Args:
            task_name: Task name
            task_func: Task function
            args: Task arguments
            kwargs: Task keyword arguments
        """
        self.task_name = task_name
        self.task_func = task_func
        self.args = args
        self.kwargs = kwargs
        self.thread = None
        self.running = False
        self.completed = False
        self.result = None
        self.error = None


class TaskManager:
    """Background task manager"""
    def __init__(self):
        """Initialize task manager"""
        self.tasks: Dict[str, Task] = {}
        self.lock = threading.Lock()
    
    def register_task(self, task_name: str, task_func: Callable, *args, **kwargs) -> Task:
        """Register task
        
        Args:
            task_name: Task name
            task_func: Task function
            args: Task arguments
            kwargs: Task keyword arguments
        
        Returns:
            Task: Task object
        """
        with self.lock:
            task = Task(task_name, task_func, *args, **kwargs)
            self.tasks[task_name] = task
            return task
    
    def execute_task(self, task_name: str) -> bool:
        """Execute task
        
        Args:
            task_name: Task name
        
        Returns:
            bool: True if task is executed, False otherwise
        """
        with self.lock:
            if task_name not in self.tasks:
                return False
            
            task = self.tasks[task_name]
            if task.running:
                return False
            
            def task_wrapper():
                try:
                    task.running = True
                    task.result = task.task_func(*task.args, **task.kwargs)
                    task.completed = True
                except Exception as e:
                    task.error = e
                finally:
                    task.running = False
            
            task.thread = threading.Thread(target=task_wrapper, daemon=True)
            task.thread.start()
            return True
    
    def cancel_task(self, task_name: str) -> bool:
        """Cancel task
        
        Args:
            task_name: Task name
        
        Returns:
            bool: True if task is cancelled, False otherwise
        """
        with self.lock:
            if task_name not in self.tasks:
                return False
            
            task = self.tasks[task_name]
            if not task.running:
                return False
            
            # Note: We can't really cancel a running thread in Python
            # This is just a placeholder
            task.running = False
            return True
    
    def query_task(self, task_name: str) -> Dict[str, Any]:
        """Query task status
        
        Args:
            task_name: Task name
        
        Returns:
            Dict: Task status
        """
        with self.lock:
            if task_name not in self.tasks:
                return {"exists": False}
            
            task = self.tasks[task_name]
            return {
                "exists": True,
                "running": task.running,
                "completed": task.completed,
                "result": task.result,
                "error": str(task.error) if task.error else None
            }
