"""Mapper for converting between CanvasDB entity and CanvasState schemas"""
from datetime import datetime

from src.models.entities import CanvasDB
from src.models.schemas import CanvasState


class CanvasMapper:
    """Mapper for Canvas entity and schemas"""
    
    @staticmethod
    def to_schema(db: CanvasDB) -> CanvasState:
        """Convert CanvasDB entity to CanvasState schema
        
        Args:
            db: CanvasDB entity from database
            
        Returns:
            CanvasState schema for API response
        """
        return CanvasState(
            id=db.id,
            projectId=db.project_id,
            nodes=db.nodes or [],
            connections=db.connections or [],
            groups=db.groups or [],
            history=db.history or [],
            historyIndex=db.history_index,
            updatedAt=db.updated_at,
        )
    
    @staticmethod
    def to_entity(schema: CanvasState) -> CanvasDB:
        """Convert CanvasState schema to CanvasDB entity
        
        Args:
            schema: CanvasState from API
            
        Returns:
            CanvasDB entity for database storage
        """
        return CanvasDB(
            id=schema.id,
            project_id=schema.projectId,
            nodes=schema.nodes,
            connections=schema.connections,
            groups=schema.groups,
            history=schema.history,
            history_index=schema.history_index,
            updated_at=schema.updated_at,
        )
    
    @staticmethod
    def update_entity(db: CanvasDB, schema: CanvasState) -> CanvasDB:
        """Update CanvasDB entity with data from CanvasState schema
        
        Args:
            db: Existing CanvasDB entity
            schema: CanvasState with new data
            
        Returns:
            Updated CanvasDB entity
        """
        db.project_id = schema.projectId
        db.nodes = schema.nodes
        db.connections = schema.connections
        db.groups = schema.groups
        db.history = schema.history
        db.history_index = schema.history_index
        db.updated_at = datetime.now().timestamp()
        
        return db
