"""
Pydantic schemas for recipe-related API operations.
"""

from typing import Optional, List
from datetime import datetime
from pydantic import BaseModel, Field, validator

from ..models.recipe import RecipePhase


class RecipeBase(BaseModel):
    """Base recipe schema with common fields."""
    name: str = Field(..., min_length=1, max_length=100, description="Recipe name")
    description: Optional[str] = Field(None, max_length=500, description="Recipe description")
    
    # Temperature goals
    heating_goal: float = Field(..., ge=40.0, le=60.0, description="Target heating temperature (°C)")
    cooling_goal: float = Field(..., ge=20.0, le=40.0, description="Target cooling temperature (°C)")
    pouring_goal: Optional[float] = Field(None, ge=20.0, le=60.0, description="Target pouring temperature (°C)")
    
    # Operating temperatures
    tank_temp: float = Field(45.0, ge=20.0, le=80.0, description="Tank operating temperature (°C)")
    fountain_temp: float = Field(32.0, ge=20.0, le=60.0, description="Fountain operating temperature (°C)")
    
    # Motor settings
    mixer_enabled: bool = Field(True, description="Enable mixer motor")
    fountain_enabled: bool = Field(True, description="Enable fountain motor")
    mold_heater_enabled: bool = Field(False, description="Enable mold heater")
    vibration_enabled: bool = Field(False, description="Enable vibration motor")
    vib_heater_enabled: bool = Field(False, description="Enable vibration heater")
    
    # Pedal control
    pedal_control_enabled: bool = Field(True, description="Enable pedal control")
    pedal_on_time: float = Field(2.0, ge=0.1, le=10.0, description="Pedal on duration (seconds)")
    pedal_off_time: float = Field(3.0, ge=0.1, le=10.0, description="Pedal off duration (seconds)")

    @validator('cooling_goal')
    def validate_cooling_goal(cls, v, values):
        """Ensure cooling goal is less than heating goal."""
        heating_goal = values.get('heating_goal')
        if heating_goal is not None and v >= heating_goal:
            raise ValueError('Cooling goal must be less than heating goal')
        return v

    @validator('pouring_goal')
    def validate_pouring_goal(cls, v, values):
        """Ensure pouring goal is within cooling and heating range."""
        if v is None:
            return v
        
        cooling_goal = values.get('cooling_goal')
        heating_goal = values.get('heating_goal')
        
        if cooling_goal is not None and v < cooling_goal:
            raise ValueError('Pouring goal must be greater than or equal to cooling goal')
        if heating_goal is not None and v > heating_goal:
            raise ValueError('Pouring goal must be less than or equal to heating goal')
        
        return v


class RecipeCreate(RecipeBase):
    """Schema for creating a new recipe."""
    pass


class RecipeUpdate(BaseModel):
    """Schema for updating an existing recipe."""
    name: Optional[str] = Field(None, min_length=1, max_length=100)
    description: Optional[str] = Field(None, max_length=500)
    
    heating_goal: Optional[float] = Field(None, ge=40.0, le=60.0)
    cooling_goal: Optional[float] = Field(None, ge=20.0, le=40.0)
    pouring_goal: Optional[float] = Field(None, ge=20.0, le=60.0)
    
    tank_temp: Optional[float] = Field(None, ge=20.0, le=80.0)
    fountain_temp: Optional[float] = Field(None, ge=20.0, le=60.0)
    
    mixer_enabled: Optional[bool] = None
    fountain_enabled: Optional[bool] = None
    mold_heater_enabled: Optional[bool] = None
    vibration_enabled: Optional[bool] = None
    vib_heater_enabled: Optional[bool] = None
    
    pedal_control_enabled: Optional[bool] = None
    pedal_on_time: Optional[float] = Field(None, ge=0.1, le=10.0)
    pedal_off_time: Optional[float] = Field(None, ge=0.1, le=10.0)
    
    is_active: Optional[bool] = None


class RecipeResponse(RecipeBase):
    """Schema for recipe API responses."""
    id: int
    created_at: datetime
    updated_at: datetime
    created_by: Optional[str] = None
    version: int
    is_active: bool
    usage_count: int
    last_used: Optional[datetime] = None

    class Config:
        from_attributes = True


class RecipeList(BaseModel):
    """Schema for recipe list responses."""
    recipes: List[RecipeResponse]
    total: int
    page: int = 1
    per_page: int = 50


class RecipeSummary(BaseModel):
    """Schema for recipe summary information."""
    id: int
    name: str
    heating_goal: float
    cooling_goal: float
    is_active: bool
    usage_count: int
    last_used: Optional[datetime] = None

    class Config:
        from_attributes = True