from sqlalchemy import Column, String, Integer, Text, DateTime, Boolean, ForeignKey
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from pydantic import BaseModel, Field
from typing import Optional, List
from datetime import datetime
import uuid

from ..core.database import Base

class NoteHighlight(Base):
    """노트 하이라이트 모델"""
    __tablename__ = "note_highlights"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    note_id = Column(UUID(as_uuid=True), ForeignKey("notes_documents.id", ondelete="CASCADE"), nullable=False)
    start_offset = Column(Integer, nullable=False)
    end_offset = Column(Integer, nullable=False)
    selected_text = Column(Text, nullable=False)
    highlight_color = Column(String(50), nullable=False, default='#FFFF00')
    highlight_type = Column(String(50), nullable=False, default='highlight')
    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)

    # 관계
    note = relationship("NoteDocument", back_populates="highlights")
    notes = relationship("NoteNote", back_populates="highlight", cascade="all, delete-orphan")

# Pydantic 모델들
class NoteHighlightBase(BaseModel):
    note_id: str
    start_offset: int
    end_offset: int
    selected_text: str
    highlight_color: str = '#FFFF00'
    highlight_type: str = 'highlight'

class NoteHighlightCreate(NoteHighlightBase):
    pass

class NoteHighlightUpdate(BaseModel):
    highlight_color: Optional[str] = None
    highlight_type: Optional[str] = None

class NoteHighlightResponse(NoteHighlightBase):
    id: str
    created_at: datetime
    updated_at: datetime
    created_by: str

    class Config:
        from_attributes = True

    @classmethod
    def from_orm(cls, obj):
        return cls(
            id=str(obj.id),
            note_id=str(obj.note_id),
            start_offset=obj.start_offset,
            end_offset=obj.end_offset,
            selected_text=obj.selected_text,
            highlight_color=obj.highlight_color,
            highlight_type=obj.highlight_type,
            created_at=obj.created_at,
            updated_at=obj.updated_at,
            created_by=obj.created_by
        )
