from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session, selectinload
from typing import List
from ...core.database import get_sync_db
from ..dependencies import get_current_user
from ...models.user import User
from ...models.note_note import NoteNote, NoteNoteCreate, NoteNoteUpdate, NoteNoteResponse
from ...models.note_document import NoteDocument
from ...models.note_highlight import NoteHighlight

router = APIRouter()

@router.get("/note/{note_id}/notes", response_model=List[NoteNoteResponse])
def get_note_notes(
    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")
    
    # 메모 조회
    notes = db.query(NoteNote).filter(
        NoteNote.note_id == note_id
    ).options(
        selectinload(NoteNote.highlight)
    ).order_by(NoteNote.created_at.desc()).all()
    
    return [NoteNoteResponse.from_orm(note) for note in notes]

@router.get("/note-highlights/{highlight_id}/notes", response_model=List[NoteNoteResponse])
def get_highlight_notes(
    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")
    
    # 메모 조회
    notes = db.query(NoteNote).filter(
        NoteNote.highlight_id == highlight_id
    ).order_by(NoteNote.created_at.desc()).all()
    
    return [NoteNoteResponse.from_orm(note) for note in notes]

@router.post("/note-notes/", response_model=NoteNoteResponse)
def create_note_note(
    note_data: NoteNoteCreate,
    db: Session = Depends(get_sync_db),
    current_user: User = Depends(get_current_user)
):
    """노트 메모 생성"""
    # 노트 존재 확인
    note = db.query(NoteDocument).filter(NoteDocument.id == note_data.note_id).first()
    if not note:
        raise HTTPException(status_code=404, detail="Note not found")
    
    # 하이라이트 존재 확인 (선택사항)
    if note_data.highlight_id:
        highlight = db.query(NoteHighlight).filter(NoteHighlight.id == note_data.highlight_id).first()
        if not highlight:
            raise HTTPException(status_code=404, detail="Highlight not found")
    
    # 메모 생성
    note_note = NoteNote(
        note_id=note_data.note_id,
        highlight_id=note_data.highlight_id,
        content=note_data.content,
        created_by=current_user.email
    )
    
    db.add(note_note)
    db.commit()
    db.refresh(note_note)
    
    return NoteNoteResponse.from_orm(note_note)

@router.put("/note-notes/{note_note_id}", response_model=NoteNoteResponse)
def update_note_note(
    note_note_id: str,
    note_data: NoteNoteUpdate,
    db: Session = Depends(get_sync_db),
    current_user: User = Depends(get_current_user)
):
    """노트 메모 수정"""
    note_note = db.query(NoteNote).filter(NoteNote.id == note_note_id).first()
    if not note_note:
        raise HTTPException(status_code=404, detail="Note not found")
    
    # 권한 확인
    if note_note.created_by != current_user.email and not current_user.is_admin:
        raise HTTPException(status_code=403, detail="Permission denied")
    
    # 업데이트
    for field, value in note_data.dict(exclude_unset=True).items():
        setattr(note_note, field, value)
    
    db.commit()
    db.refresh(note_note)
    
    return NoteNoteResponse.from_orm(note_note)

@router.delete("/note-notes/{note_note_id}")
def delete_note_note(
    note_note_id: str,
    db: Session = Depends(get_sync_db),
    current_user: User = Depends(get_current_user)
):
    """노트 메모 삭제"""
    note_note = db.query(NoteNote).filter(NoteNote.id == note_note_id).first()
    if not note_note:
        raise HTTPException(status_code=404, detail="Note not found")
    
    # 권한 확인
    if note_note.created_by != current_user.email and not current_user.is_admin:
        raise HTTPException(status_code=403, detail="Permission denied")
    
    db.delete(note_note)
    db.commit()
    
    return {"message": "Note deleted successfully"}
