from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from ...core.database import get_sync_db
from ..dependencies import get_current_user
from ...models.user import User
from ...models.note_highlight import NoteHighlight, NoteHighlightCreate, NoteHighlightUpdate, NoteHighlightResponse
from ...models.note_document import NoteDocument

router = APIRouter()

@router.get("/note/{note_id}/highlights", response_model=List[NoteHighlightResponse])
def get_note_highlights(
    note_id: str,
    db: Session = Depends(get_sync_db),
    current_user: User = Depends(get_current_user)
):
    """특정 노트의 하이라이트 목록 조회"""
    # 노트 존재 확인
    note = db.query(NoteDocument).filter(NoteDocument.id == note_id).first()
    if not note:
        raise HTTPException(status_code=404, detail="Note not found")
    
    # 하이라이트 조회
    highlights = db.query(NoteHighlight).filter(
        NoteHighlight.note_id == note_id
    ).order_by(NoteHighlight.start_offset).all()
    
    return [NoteHighlightResponse.from_orm(highlight) for highlight in highlights]

@router.post("/note-highlights/", response_model=NoteHighlightResponse)
def create_note_highlight(
    highlight_data: NoteHighlightCreate,
    db: Session = Depends(get_sync_db),
    current_user: User = Depends(get_current_user)
):
    """노트 하이라이트 생성"""
    # 노트 존재 확인
    note = db.query(NoteDocument).filter(NoteDocument.id == highlight_data.note_id).first()
    if not note:
        raise HTTPException(status_code=404, detail="Note not found")
    
    # 하이라이트 생성
    highlight = NoteHighlight(
        note_id=highlight_data.note_id,
        start_offset=highlight_data.start_offset,
        end_offset=highlight_data.end_offset,
        selected_text=highlight_data.selected_text,
        highlight_color=highlight_data.highlight_color,
        highlight_type=highlight_data.highlight_type,
        created_by=current_user.email
    )
    
    db.add(highlight)
    db.commit()
    db.refresh(highlight)
    
    return NoteHighlightResponse.from_orm(highlight)

@router.put("/note-highlights/{highlight_id}", response_model=NoteHighlightResponse)
def update_note_highlight(
    highlight_id: str,
    highlight_data: NoteHighlightUpdate,
    db: Session = Depends(get_sync_db),
    current_user: User = Depends(get_current_user)
):
    """노트 하이라이트 수정"""
    highlight = db.query(NoteHighlight).filter(NoteHighlight.id == highlight_id).first()
    if not highlight:
        raise HTTPException(status_code=404, detail="Highlight not found")
    
    # 권한 확인
    if highlight.created_by != current_user.email and not current_user.is_admin:
        raise HTTPException(status_code=403, detail="Permission denied")
    
    # 업데이트
    for field, value in highlight_data.dict(exclude_unset=True).items():
        setattr(highlight, field, value)
    
    db.commit()
    db.refresh(highlight)
    
    return NoteHighlightResponse.from_orm(highlight)

@router.delete("/note-highlights/{highlight_id}")
def delete_note_highlight(
    highlight_id: str,
    db: Session = Depends(get_sync_db),
    current_user: User = Depends(get_current_user)
):
    """노트 하이라이트 삭제"""
    highlight = db.query(NoteHighlight).filter(NoteHighlight.id == highlight_id).first()
    if not highlight:
        raise HTTPException(status_code=404, detail="Highlight not found")
    
    # 권한 확인
    if highlight.created_by != current_user.email and not current_user.is_admin:
        raise HTTPException(status_code=403, detail="Permission denied")
    
    db.delete(highlight)
    db.commit()
    
    return {"message": "Highlight deleted successfully"}
