@app.route('/video/<int:video_id>', methods=['GET', 'POST'])
def video(video_id):
    current_video = db_sess.query(Video).get(video_id)
    if current_video is None:
        return page_not_found('')

    # Проверяем, разрешены ли комментарии для этого видео
    comments_enabled = current_video.comments_enabled

    # Получаем автора видео
    author = current_video.author
    all_videos = db_sess.query(Video).all()
    # Проверяем, поставил ли текущий пользователь лайк и подписан ли
    like = False
    subscription = False
    # Check if the user is logged in
    if current_user.is_authenticated:
        # Check if the user has already viewed the video
        view_exists = db_sess.query(VideoView).filter_by(
            user_id=current_user.id, video_id=video_id).first()

        # If not, increment the view count and add a record to video_views
        if not view_exists:
            current_video.views += 1
            new_view = VideoView(user_id=current_user.id, video_id=video_id)
            db_sess.add(new_view)
            db_sess.commit()
    if current_user.is_authenticated:
        likes = json.loads(current_user.likes)
        subscriptions = json.loads(current_user.subscriptions)
        if video_id in likes:
            like = True
        if current_video.author in subscriptions:
            subscription = True

    # Обрабатываем форму комментария
    # Обрабатываем форму комментария только если комментарии включены
    form = CommentForm()
    if comments_enabled and form.validate_on_submit():
        if current_user.is_authenticated and not current_user.is_blocked:
            # Добавление комментария
            comment = Comment(
                content=form.content.data,
                user_id=current_user.id,
                video_id=video_id,
                parent_id=form.parent_id.data or None
            )
            db_sess.add(comment)
            db_sess.commit()
            flash('Комментарий добавлен!', 'success')
            return redirect(url_for('video', video_id=video_id))
        else:
            flash('Вы не можете оставить комментарий.', 'danger')
            return redirect

    # Получаем комментарии к видео


    comments = db_sess.query(Comment).filter(Comment.video_id == video_id).options(
        joinedload(Comment.user),
        joinedload(Comment.parent).joinedload(Comment.user),
        joinedload(Comment.replies).joinedload(Comment.user)
    ).order_by(Comment.datetime.desc()).all()  # Изменено на desc() для сортировки в обратном порядке

    # Создаем словарь комментариев по id для удобства доступа
    comments_by_id = {comment.id: comment for comment in comments}

    # Строим дерево комментариев
    root_comments = []
    for comment in comments:
        if comment.parent_id is None:
            root_comments.append(comment)
        else:
            parent = comments_by_id.get(comment.parent_id)
            if parent:
                if not hasattr(parent, 'replies_sorted'):
                    parent.replies_sorted = []
                parent.replies_sorted.append(comment)
    last_videos = all_videos[len(all_videos) - 10:][::-1]
    params = {
        'title': f"{current_video.title} - {author.name} {author.surname}",
        'current_video': current_video,
        'video_src': url_for("static", filename=f'vid/{video_id}.mp4'),
        'author': author,
        'like': like,

        'subscription': subscription,
        'db_sess': db_sess,
        'comments': root_comments,
        'User': User,
        'authenticated': current_user.is_authenticated,
        'current_user': current_user,
        'avatar_url': url_for('static', filename=f'avatars/{author.avatar}'),
        'comments': comments,
        'last_videos': last_videos,
        'form': form
    }
    return render_template('video.html', **params)
# data/videos.py

import sqlalchemy
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Boolean
from sqlalchemy.orm import relationship
from data.db_session import SqlAlchemyBase
from sqlalchemy_serializer import SerializerMixin
from datetime import datetime

class Video(SqlAlchemyBase, SerializerMixin):
    __tablename__ = 'videos'

    id = Column(Integer, primary_key=True, unique=True, autoincrement=True, nullable=False)
    title = Column(String, nullable=False)
    author_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    description = Column(String, nullable=False, default='')
    likes = Column(Integer, nullable=False, default=0)
    datetime = Column(DateTime, nullable=False, default=datetime.utcnow)
    comments_enabled = Column(Boolean, default=True)  # Новое поле
    privacy = Column(Integer, nullable=False, default=3)  # New field for privacy setting
    comments = relationship('Comment', back_populates='video', cascade='all, delete-orphan')
    author = relationship('User', back_populates='videos')
    views = sqlalchemy.Column(sqlalchemy.Integer, nullable=False, default=0)  # New field for view count