from flask import Blueprint, request, jsonify
from src.models.user import db, User
from src.utils.user_ref import resolve_user_ref
from src.models.sns import SnsPost, SnsLike, SnsComment, Follow
import json

sns_bp = Blueprint('sns', __name__)

@sns_bp.route('/sns/posts', methods=['GET'])
def get_sns_posts():
    """SNS 게시글 피드 조회"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        user_id = request.args.get('user_id', type=str)
        
        query = SnsPost.query
        
        # 특정 사용자의 게시글만 조회
        if user_id:
            query = query.filter(SnsPost.author_id == user_id)
        
        posts = query.order_by(SnsPost.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return jsonify({
            'posts': [post.to_dict() for post in posts.items],
            'total': posts.total,
            'pages': posts.pages,
            'current_page': page
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@sns_bp.route('/sns/posts', methods=['POST'])
def create_sns_post():
    """SNS 게시글 작성"""
    try:
        data = request.get_json()
        
        # 필수 필드 검증
        required_fields = ['content', 'author_id']
        for field in required_fields:
            if field not in data:
                return jsonify({'error': f'{field} is required'}), 400
        
        # 사용자 존재 확인
        user = resolve_user_ref(data['author_id'])
        if not user:
            return jsonify({'error': 'User not found'}), 404
        
        post = SnsPost(
            content=data['content'],
            author_id=user.user_id,
            image_urls=json.dumps(data.get('image_urls', [])),
            hashtags=json.dumps(data.get('hashtags', []))
        )
        
        db.session.add(post)
        db.session.commit()
        
        return jsonify(post.to_dict()), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@sns_bp.route('/sns/posts/<int:post_id>', methods=['GET'])
def get_sns_post(post_id):
    """SNS 게시글 상세 조회"""
    try:
        post = SnsPost.query.get_or_404(post_id)
        
        post_data = post.to_dict()
        post_data['comments'] = [comment.to_dict() for comment in post.comments if comment.parent_id is None]
        
        return jsonify(post_data)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@sns_bp.route('/sns/posts/<int:post_id>/like', methods=['POST'])
def like_sns_post(post_id):
    """SNS 게시글 좋아요"""
    try:
        post = SnsPost.query.get_or_404(post_id)
        data = request.get_json()
        
        if 'user_id' not in data:
            return jsonify({'error': 'user_id is required'}), 400
        lu = resolve_user_ref(data['user_id'])
        if not lu:
            return jsonify({'error': 'User not found'}), 404
        lid = lu.user_id

        # 이미 좋아요했는지 확인
        existing_like = SnsLike.query.filter_by(
            post_id=post_id,
            user_id=lid,
        ).first()
        
        if existing_like:
            # 좋아요 취소
            db.session.delete(existing_like)
            db.session.commit()
            return jsonify({'liked': False, 'like_count': len(post.likes)})
        else:
            # 좋아요 추가
            like = SnsLike(
                post_id=post_id,
                user_id=lid,
            )
            db.session.add(like)
            db.session.commit()
            return jsonify({'liked': True, 'like_count': len(post.likes)})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@sns_bp.route('/sns/posts/<int:post_id>/comments', methods=['POST'])
def create_sns_comment(post_id):
    """SNS 게시글 댓글 작성"""
    try:
        post = SnsPost.query.get_or_404(post_id)
        data = request.get_json()
        
        # 필수 필드 검증
        required_fields = ['content', 'author_id']
        for field in required_fields:
            if field not in data:
                return jsonify({'error': f'{field} is required'}), 400
        
        au = resolve_user_ref(data['author_id'])
        if not au:
            return jsonify({'error': 'User not found'}), 404
        comment = SnsComment(
            content=data['content'],
            post_id=post_id,
            author_id=au.user_id,
            parent_id=data.get('parent_id')
        )
        
        db.session.add(comment)
        db.session.commit()
        
        return jsonify(comment.to_dict()), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@sns_bp.route('/sns/follow', methods=['POST'])
def follow_user():
    """사용자 팔로우"""
    try:
        data = request.get_json()
        
        required_fields = ['follower_id', 'following_id']
        for field in required_fields:
            if field not in data:
                return jsonify({'error': f'{field} is required'}), 400
        
        fu = resolve_user_ref(data['follower_id'])
        tu = resolve_user_ref(data['following_id'])
        if not fu or not tu:
            return jsonify({'error': 'User not found'}), 404
        fid, tid = fu.user_id, tu.user_id
        if fid == tid:
            return jsonify({'error': 'Cannot follow yourself'}), 400
        
        # 이미 팔로우했는지 확인
        existing_follow = Follow.query.filter_by(
            follower_id=fid,
            following_id=tid,
        ).first()
        
        if existing_follow:
            # 언팔로우
            db.session.delete(existing_follow)
            db.session.commit()
            return jsonify({'following': False})
        else:
            # 팔로우
            follow = Follow(
                follower_id=fid,
                following_id=tid,
            )
            db.session.add(follow)
            db.session.commit()
            return jsonify({'following': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@sns_bp.route('/sns/users/<string:business_user_id>/profile', methods=['GET'])
def get_user_profile(business_user_id):
    """사용자 프로필 조회 (업무 user_id)"""
    try:
        user = User.query.filter_by(user_id=business_user_id).first_or_404()

        follower_count = Follow.query.filter_by(following_id=business_user_id).count()
        following_count = Follow.query.filter_by(follower_id=business_user_id).count()

        post_count = SnsPost.query.filter_by(author_id=business_user_id).count()
        
        profile = {
            'user': user.to_dict(),
            'follower_count': follower_count,
            'following_count': following_count,
            'post_count': post_count
        }
        
        return jsonify(profile)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@sns_bp.route('/sns/users/<int:user_id>/followers', methods=['GET'])
def get_followers(user_id):
    """팔로워 목록 조회"""
    try:
        follows = Follow.query.filter_by(following_id=user_id).all()
        followers = [follow.follower.to_dict() for follow in follows]
        return jsonify(followers)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@sns_bp.route('/sns/users/<int:user_id>/following', methods=['GET'])
def get_following(user_id):
    """팔로잉 목록 조회"""
    try:
        follows = Follow.query.filter_by(follower_id=user_id).all()
        following = [follow.following.to_dict() for follow in follows]
        return jsonify(following)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@sns_bp.route('/sns/hashtags/<hashtag>', methods=['GET'])
def get_posts_by_hashtag(hashtag):
    """해시태그별 게시글 조회"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        
        # JSON 필드에서 해시태그 검색 (SQLite에서는 제한적)
        posts = SnsPost.query.filter(
            SnsPost.hashtags.like(f'%"{hashtag}"%')
        ).order_by(SnsPost.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return jsonify({
            'posts': [post.to_dict() for post in posts.items],
            'total': posts.total,
            'pages': posts.pages,
            'current_page': page,
            'hashtag': hashtag
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

