"""
노트북 모델
"""
from sqlalchemy import Column, String, Boolean, DateTime, Integer, Text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from pydantic import BaseModel, Field
from typing import List, Optional
from datetime import datetime
import uuid

from ..core.database import Base


class Notebook(Base):
    """노트북 테이블"""
    __tablename__ = "notebooks"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    title = Column(String(500), nullable=False)
    description = Column(Text, nullable=True)
    color = Column(String(7), default='#3B82F6')  # 헥스 컬러 코드
    icon = Column(String(50), default='book')  # FontAwesome 아이콘
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    created_by = Column(String(100), nullable=False)
    is_active = Column(Boolean, default=True)
    sort_order = Column(Integer, default=0)

    # 관계 설정 (노트들)
    notes = relationship("NoteDocument", back_populates="notebook")


# Pydantic 모델들
class NotebookBase(BaseModel):
    title: str = Field(..., min_length=1, max_length=500)
    description: Optional[str] = None
    color: str = Field(default='#3B82F6', pattern=r'^#[0-9A-Fa-f]{6}$')
    icon: str = Field(default='book', min_length=1, max_length=50)
    is_active: bool = True
    sort_order: int = 0


class NotebookCreate(NotebookBase):
    pass


class NotebookUpdate(BaseModel):
    title: Optional[str] = Field(None, min_length=1, max_length=500)
    description: Optional[str] = None
    color: Optional[str] = Field(None, pattern=r'^#[0-9A-Fa-f]{6}$')
    icon: Optional[str] = Field(None, min_length=1, max_length=50)
    is_active: Optional[bool] = None
    sort_order: Optional[int] = None


class NotebookResponse(NotebookBase):
    id: str
    created_at: datetime
    updated_at: datetime
    created_by: str
    note_count: int = 0  # 포함된 노트 개수
    
    class Config:
        from_attributes = True
        
    @classmethod
    def from_orm(cls, obj, note_count=0):
        """ORM 객체에서 Pydantic 모델로 변환"""
        data = {
            'id': str(obj.id),
            'title': obj.title,
            'description': obj.description,
            'color': obj.color,
            'icon': obj.icon,
            'created_at': obj.created_at,
            'updated_at': obj.updated_at,
            'created_by': obj.created_by,
            'is_active': obj.is_active,
            'sort_order': obj.sort_order,
            'note_count': note_count,
        }
        return cls(**data)


class NotebookListItem(BaseModel):
    """노트북 목록용 간소화된 모델"""
    id: str
    title: str
    description: Optional[str]
    color: str
    icon: str
    created_at: datetime
    updated_at: datetime
    created_by: str
    is_active: bool
    note_count: int = 0
    
    class Config:
        from_attributes = True
        
    @classmethod
    def from_orm(cls, obj, note_count=0):
        """ORM 객체에서 Pydantic 모델로 변환"""
        data = {
            'id': str(obj.id),
            'title': obj.title,
            'description': obj.description,
            'color': obj.color,
            'icon': obj.icon,
            'created_at': obj.created_at,
            'updated_at': obj.updated_at,
            'created_by': obj.created_by,
            'is_active': obj.is_active,
            'note_count': note_count,
        }
        return cls(**data)


class NotebookStats(BaseModel):
    """노트북 통계 정보"""
    total_notebooks: int
    active_notebooks: int
    total_notes: int
    notes_without_notebook: int
