"""Base model for all database models.

This module defines the base class that all SQLAlchemy models inherit from.
"""

from datetime import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declared_attr

from src.config.database import Base as DeclarativeBase


class BaseModel(DeclarativeBase):
    """Base model with common fields.
    
    All models should inherit from this class to get:
    - id (primary key)
    - created_at
    - updated_at
    - Automatic table naming
    """
    
    __abstract__ = True
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(
        DateTime,
        default=datetime.utcnow,
        onupdate=datetime.utcnow,
        nullable=False
    )
    
    @declared_attr
    def __tablename__(cls) -> str:
        """Generate table name from class name.
        
        Converts PascalCase to snake_case.
        Example: UserModel -> user_model
        """
        import re
        name = cls.__name__
        # Convert PascalCase to snake_case
        name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
        name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()
        return name
    
    def __repr__(self) -> str:
        """String representation."""
        return f"<{self.__class__.__name__}(id={self.id})>"

