from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from typing import List, Optional
from uuid import UUID
from ..database import get_db
from ..models.comment import Comment
from ..models.stream import Stream
from ..models.user import User
from ..schemas.comment import CommentCreate, CommentUpdate, CommentResponse
from ..auth import get_current_active_user, get_current_user_optional, require_permission, require_any_permission
from ..config import settings

router = APIRouter(prefix="/api/streams/{stream_id}/comments", tags=["comments"])


@router.get("", response_model=List[CommentResponse])
async def list_comments(
    stream_id: UUID,
    skip: int = 0,
    limit: int = 50,
    db: Session = Depends(get_db),
    current_user: Optional[User] = Depends(get_current_user_optional)
):
    # Check if stream exists
    stream = db.query(Stream).filter(Stream.id == stream_id).first()
    if not stream:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Stream not found"
        )
    
    # Check access - public streams can be accessed without authentication
    if not stream.is_public:
        if not current_user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Authentication required for private streams"
            )
        if stream.created_by != current_user.id and current_user.role.name != "admin":
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Access denied"
            )
    
    comments = db.query(Comment).filter(
        Comment.stream_id == stream_id
    ).order_by(Comment.created_at).offset(skip).limit(limit).all()
    
    return comments


@router.post("", response_model=CommentResponse, status_code=status.HTTP_201_CREATED)
async def create_comment(
    stream_id: UUID,
    comment_data: CommentCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_permission("comment:create"))
):
    # Check if stream exists and user has access
    stream = db.query(Stream).filter(Stream.id == stream_id).first()
    if not stream:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Stream not found"
        )
    
    if not stream.is_public and stream.created_by != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Access denied"
        )
    
    # If parent_id is provided, check if it exists
    if comment_data.parent_id:
        parent_comment = db.query(Comment).filter(
            Comment.id == comment_data.parent_id,
            Comment.stream_id == stream_id
        ).first()
        if not parent_comment:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Parent comment not found"
            )
    
    new_comment = Comment(
        stream_id=stream_id,
        user_id=current_user.id,
        username=current_user.username,
        content=comment_data.content,
        parent_id=comment_data.parent_id
    )
    db.add(new_comment)
    db.commit()
    db.refresh(new_comment)
    
    return new_comment


@router.put("/{comment_id}", response_model=CommentResponse)
async def update_comment(
    stream_id: UUID,
    comment_id: UUID,
    comment_data: CommentUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_any_permission(["comment:update", "comment:update:own"]))
):
    comment = db.query(Comment).filter(
        Comment.id == comment_id,
        Comment.stream_id == stream_id
    ).first()
    
    if not comment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Comment not found"
        )
    
    # Check ownership
    if comment.user_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Access denied"
        )
    
    comment.content = comment_data.content
    db.commit()
    db.refresh(comment)
    
    return comment


@router.delete("/{comment_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_comment(
    stream_id: UUID,
    comment_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_any_permission(["comment:delete", "comment:delete:own"]))
):
    comment = db.query(Comment).filter(
        Comment.id == comment_id,
        Comment.stream_id == stream_id
    ).first()
    
    if not comment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Comment not found"
        )
    
    # Check ownership
    if comment.user_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Access denied"
        )
    
    db.delete(comment)
    db.commit()
    
    return None
