"""Simple gateway orchestrator with in-memory task queue."""

from typing import Dict, List, Optional, Any
from datetime import datetime
from .task import Task, TaskStatus


class SimpleGatewayOrchestrator:
    """Simple in-memory gateway orchestrator for distributed task management."""

    def __init__(self):
        """Initialize gateway orchestrator."""
        self._devices: Dict[str, dict] = {}
        self._tasks: Dict[str, Task] = {}
        self._task_counter = 0

    def register_device(self, device_id: str, metadata: dict = None) -> Dict[str, Any]:
        """Register a device.
        
        Args:
            device_id: Device identifier
            metadata: Device metadata
            
        Returns:
            Registration result
        """
        if device_id in self._devices:
            return {
                "success": False,
                "message": f"Device already registered: {device_id}"
            }
        
        self._devices[device_id] = {
            "device_id": device_id,
            "registered_at": datetime.now(),
            "metadata": metadata or {},
            "active": True
        }
        
        return {
            "success": True,
            "message": f"Device registered: {device_id}",
            "device_id": device_id
        }

    def unregister_device(self, device_id: str) -> Dict[str, Any]:
        """Unregister a device.
        
        Args:
            device_id: Device identifier
            
        Returns:
            Unregistration result
        """
        if device_id not in self._devices:
            return {
                "success": False,
                "message": f"Device not found: {device_id}"
            }
        
        del self._devices[device_id]
        
        return {
            "success": True,
            "message": f"Device unregistered: {device_id}"
        }

    def queue_task(self, user_input: str, metadata: dict = None) -> Task:
        """Queue a new task.
        
        Args:
            user_input: User's natural language input
            metadata: Task metadata
            
        Returns:
            Created task
        """
        self._task_counter += 1
        task_id = f"task_{self._task_counter}_{datetime.now().timestamp()}"
        
        task = Task(
            task_id=task_id,
            user_input=user_input,
            status=TaskStatus.PENDING,
            metadata=metadata or {}
        )
        
        self._tasks[task_id] = task
        return task

    def fetch_task(self, device_id: str) -> Optional[Task]:
        """Fetch next pending task for device.
        
        Args:
            device_id: Device identifier
            
        Returns:
            Task or None if no tasks available
        """
        if device_id not in self._devices:
            return None
        
        # Find first pending task
        for task in self._tasks.values():
            if task.status == TaskStatus.PENDING:
                task.status = TaskStatus.ASSIGNED
                task.device_id = device_id
                task.assigned_at = datetime.now()
                return task
        
        return None

    def acknowledge_task(self, task_id: str, result: Dict[str, Any]) -> Dict[str, Any]:
        """Acknowledge task completion.
        
        Args:
            task_id: Task identifier
            result: Execution result
            
        Returns:
            Acknowledgment result
        """
        task = self._tasks.get(task_id)
        
        if not task:
            return {
                "success": False,
                "message": f"Task not found: {task_id}"
            }
        
        if task.status == TaskStatus.COMPLETED:
            return {
                "success": False,
                "message": "Task already completed"
            }
        
        task.status = TaskStatus.COMPLETED if result.get("success") else TaskStatus.FAILED
        task.result = result
        task.completed_at = datetime.now()
        
        return {
            "success": True,
            "message": f"Task acknowledged: {task_id}",
            "task_id": task_id
        }

    def get_task(self, task_id: str) -> Optional[Task]:
        """Get task by ID.
        
        Args:
            task_id: Task identifier
            
        Returns:
            Task or None
        """
        return self._tasks.get(task_id)

    def list_tasks(self, status: Optional[TaskStatus] = None) -> List[Task]:
        """List tasks, optionally filtered by status.
        
        Args:
            status: Optional status filter
            
        Returns:
            List of tasks
        """
        if status:
            return [t for t in self._tasks.values() if t.status == status]
        return list(self._tasks.values())

    def list_devices(self) -> List[dict]:
        """List registered devices.
        
        Returns:
            List of devices
        """
        return list(self._devices.values())

    def get_statistics(self) -> dict:
        """Get queue statistics.
        
        Returns:
            Statistics dictionary
        """
        total_tasks = len(self._tasks)
        pending = sum(1 for t in self._tasks.values() if t.status == TaskStatus.PENDING)
        assigned = sum(1 for t in self._tasks.values() if t.status == TaskStatus.ASSIGNED)
        completed = sum(1 for t in self._tasks.values() if t.status == TaskStatus.COMPLETED)
        failed = sum(1 for t in self._tasks.values() if t.status == TaskStatus.FAILED)
        
        return {
            "total_tasks": total_tasks,
            "total_devices": len(self._devices),
            "pending": pending,
            "assigned": assigned,
            "completed": completed,
            "failed": failed
        }
