from typing import Dict, Any, Callable, Optional
from datetime import datetime
import importlib
from .interfaces import TaskModel

class Task(TaskModel):
    """Task model implementation."""
    
    def __init__(self, 
                 task_name: str, 
                 trigger_time: datetime, 
                 execution_function: Callable, 
                 parameters: Dict[str, Any] = None, 
                 max_executions: int = 1, 
                 retry_count: int = 0, 
                 retry_interval: int = 60):
        self.task_name = task_name
        self.trigger_time = trigger_time
        self.execution_function = execution_function
        self.parameters = parameters or {}
        self.max_executions = max_executions
        self.retry_count = retry_count
        self.retry_interval = retry_interval
        self.execution_count = 0
        # Store function path for serialization
        self.function_module = execution_function.__module__
        self.function_name = execution_function.__name__
    
    def get_task_name(self) -> str:
        return self.task_name
    
    def get_trigger_time(self) -> datetime:
        return self.trigger_time
    
    def get_execution_function(self) -> Callable:
        return self.execution_function
    
    def get_parameters(self) -> Dict[str, Any]:
        return self.parameters
    
    def get_max_executions(self) -> int:
        return self.max_executions
    
    def get_retry_count(self) -> int:
        return self.retry_count
    
    def get_retry_interval(self) -> int:
        return self.retry_interval
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert task to dictionary for storage."""
        return {
            'task_name': self.task_name,
            'trigger_time': self.trigger_time.isoformat(),
            'function_module': self.function_module,
            'function_name': self.function_name,
            'parameters': self.parameters,
            'max_executions': self.max_executions,
            'retry_count': self.retry_count,
            'retry_interval': self.retry_interval,
            'execution_count': self.execution_count
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Task':
        """Create task from dictionary."""
        # Load execution function from module path
        function_module = data.get('function_module')
        function_name = data.get('function_name')
        execution_function = None
        
        if function_module and function_name:
            try:
                module = importlib.import_module(function_module)
                execution_function = getattr(module, function_name)
            except (ImportError, AttributeError):
                print(f"Error loading function {function_name} from module {function_module}")
                execution_function = lambda: None
        else:
            execution_function = lambda: None
        
        return cls(
            task_name=data['task_name'],
            trigger_time=datetime.fromisoformat(data['trigger_time']),
            execution_function=execution_function,
            parameters=data.get('parameters', {}),
            max_executions=data.get('max_executions', 1),
            retry_count=data.get('retry_count', 0),
            retry_interval=data.get('retry_interval', 60)
        )
