"""Mapper for converting between EpisodeDB entity and Episode schemas"""
import uuid
from datetime import datetime

from src.models.entities import EpisodeDB
from src.models.schemas import (
    Episode,
    CreateEpisodeRequest,
    UpdateEpisodeRequest,
)


class EpisodeMapper:
    """Mapper for Episode entity and schemas"""
    
    @staticmethod
    def to_schema(db: EpisodeDB) -> Episode:
        """Convert EpisodeDB entity to Episode schema
        
        Args:
            db: EpisodeDB entity from database
            
        Returns:
            Episode schema for API response
        """
        return Episode(
            id=db.id,
            title=db.title,
            order=db.order_index,
            desc=db.desc,
            content=db.content,
            status=db.status,
        )
    
    @staticmethod
    def to_entity(
        schema: CreateEpisodeRequest,
        project_id: str,
        episode_id: str = None
    ) -> EpisodeDB:
        """Convert CreateEpisodeRequest schema to EpisodeDB entity
        
        Args:
            schema: CreateEpisodeRequest from API
            project_id: Project ID this episode belongs to
            episode_id: Optional episode ID (generated if not provided)
            
        Returns:
            EpisodeDB entity for database storage
        """
        return EpisodeDB(
            id=episode_id or str(uuid.uuid4()),
            project_id=project_id,
            order_index=schema.order,
            title=schema.title,
            desc=schema.desc,
            status=schema.status,
        )
    
    @staticmethod
    def update_entity(db: EpisodeDB, schema: UpdateEpisodeRequest) -> EpisodeDB:
        """Update EpisodeDB entity with data from UpdateEpisodeRequest schema
        
        Args:
            db: Existing EpisodeDB entity
            schema: UpdateEpisodeRequest with new data
            
        Returns:
            Updated EpisodeDB entity
        """
        if schema.title is not None:
            db.title = schema.title
        
        if schema.order is not None:
            db.order_index = schema.order
        
        if schema.desc is not None:
            db.desc = schema.desc
        
        if schema.status is not None:
            db.status = schema.status
        
        return db
