# 文章草稿 API 视图
# 提供草稿的自动保存、获取和恢复功能

import json
import logging
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from blog.models_draft import ArticleDraft
from blog.models import Article

logger = logging.getLogger(__name__)


@login_required
@require_http_methods(["POST"])
def save_draft_api(request):
    """
    自动保存草稿 API

    POST 参数：
        - title: 文章标题
        - body: 文章正文
        - article_id: 文章ID（编辑现有文章时）
        - category_id: 分类ID
        - tags: 标签ID列表（JSON）
        - status: 状态
        - comment_status: 评论状态
        - type: 类型
        - session_id: 会话ID

    返回：
        JSON: {success: true, draft_id: xxx, message: xxx}
    """
    try:
        data = json.loads(request.body)

        title = data.get('title', '')
        body = data.get('body', '')
        article_id = data.get('article_id')
        category_id = data.get('category_id')
        tags_data = data.get('tags', [])
        status = data.get('status', 'd')
        comment_status = data.get('comment_status', 'o')
        type_value = data.get('type', 'a')
        session_id = data.get('session_id', '')

        # 保存草稿
        draft = ArticleDraft.save_draft(
            user=request.user,
            title=title,
            body=body,
            article_id=article_id,
            category_id=category_id,
            tags_data=tags_data,
            status=status,
            comment_status=comment_status,
            type=type_value,
            session_id=session_id
        )

        return JsonResponse({
            'success': True,
            'draft_id': draft.id,
            'message': '草稿已自动保存',
            'last_update': draft.last_update_time.strftime('%Y-%m-%d %H:%M:%S')
        })

    except Exception as e:
        logger.error(f"保存草稿失败: {e}", exc_info=True)
        return JsonResponse({
            'success': False,
            'message': f'保存草稿失败: {str(e)}'
        }, status=500)


@login_required
@require_http_methods(["GET"])
def get_draft_api(request):
    """
    获取草稿 API

    GET 参数：
        - article_id: 文章ID（获取该文章的草稿）
        - session_id: 会话ID（获取该会话的草稿）
        - draft_id: 草稿ID（直接获取指定草稿）

    返回：
        JSON: {success: true, draft: {...}}
    """
    try:
        article_id = request.GET.get('article_id')
        session_id = request.GET.get('session_id')
        draft_id = request.GET.get('draft_id')

        draft = None

        if draft_id:
            draft = ArticleDraft.objects.filter(
                id=draft_id,
                author=request.user,
                is_published=False
            ).first()
        elif session_id:
            draft = ArticleDraft.objects.filter(
                author=request.user,
                session_id=session_id,
                is_published=False
            ).first()
        elif article_id:
            draft = ArticleDraft.objects.filter(
                author=request.user,
                article_id=article_id,
                is_published=False
            ).first()
        else:
            # 获取最新的未发布草稿
            draft = ArticleDraft.objects.filter(
                author=request.user,
                is_published=False
            ).first()

        if draft:
            return JsonResponse({
                'success': True,
                'draft': {
                    'id': draft.id,
                    'title': draft.title,
                    'body': draft.body,
                    'article_id': draft.article_id,
                    'category_id': draft.category_id,
                    'tags': draft.tags_data,
                    'status': draft.status,
                    'comment_status': draft.comment_status,
                    'type': draft.type,
                    'last_update': draft.last_update_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'session_id': draft.session_id
                }
            })
        else:
            return JsonResponse({
                'success': False,
                'message': '未找到草稿'
            }, status=404)

    except Exception as e:
        logger.error(f"获取草稿失败: {e}", exc_info=True)
        return JsonResponse({
            'success': False,
            'message': f'获取草稿失败: {str(e)}'
        }, status=500)


@login_required
@require_http_methods(["GET"])
def list_drafts_api(request):
    """
    获取用户的所有草稿列表 API

    返回：
        JSON: {success: true, drafts: [...]}
    """
    try:
        drafts = ArticleDraft.objects.filter(
            author=request.user,
            is_published=False
        ).order_by('-last_update_time')[:20]

        drafts_data = []
        for draft in drafts:
            drafts_data.append({
                'id': draft.id,
                'title': draft.title or '(无标题)',
                'preview': draft.get_preview_text(50),
                'article_id': draft.article_id,
                'last_update': draft.last_update_time.strftime('%Y-%m-%d %H:%M:%S'),
                'creation_time': draft.creation_time.strftime('%Y-%m-%d %H:%M:%S')
            })

        return JsonResponse({
            'success': True,
            'drafts': drafts_data,
            'count': len(drafts_data)
        })

    except Exception as e:
        logger.error(f"获取草稿列表失败: {e}", exc_info=True)
        return JsonResponse({
            'success': False,
            'message': f'获取草稿列表失败: {str(e)}'
        }, status=500)


@login_required
@require_http_methods(["POST"])
def delete_draft_api(request):
    """
    删除草稿 API

    POST 参数：
        - draft_id: 草稿ID

    返回：
        JSON: {success: true, message: xxx}
    """
    try:
        data = json.loads(request.body)
        draft_id = data.get('draft_id')

        if not draft_id:
            return JsonResponse({
                'success': False,
                'message': '缺少 draft_id 参数'
            }, status=400)

        draft = ArticleDraft.objects.filter(
            id=draft_id,
            author=request.user
        ).first()

        if draft:
            draft.delete()
            return JsonResponse({
                'success': True,
                'message': '草稿已删除'
            })
        else:
            return JsonResponse({
                'success': False,
                'message': '未找到草稿'
            }, status=404)

    except Exception as e:
        logger.error(f"删除草稿失败: {e}", exc_info=True)
        return JsonResponse({
            'success': False,
            'message': f'删除草稿失败: {str(e)}'
        }, status=500)


@login_required
@require_http_methods(["POST"])
def apply_draft_api(request):
    """
    应用草稿到文章 API

    POST 参数：
        - draft_id: 草稿ID

    返回：
        JSON: {success: true, article_id: xxx, message: xxx}
    """
    try:
        data = json.loads(request.body)
        draft_id = data.get('draft_id')

        if not draft_id:
            return JsonResponse({
                'success': False,
                'message': '缺少 draft_id 参数'
            }, status=400)

        draft = ArticleDraft.objects.filter(
            id=draft_id,
            author=request.user,
            is_published=False
        ).first()

        if not draft:
            return JsonResponse({
                'success': False,
                'message': '未找到草稿'
            }, status=404)

        # 应用草稿到文章
        article = draft.apply_to_article()

        return JsonResponse({
            'success': True,
            'article_id': article.id,
            'message': '草稿已应用到文章',
            'article_url': article.get_absolute_url()
        })

    except Exception as e:
        logger.error(f"应用草稿失败: {e}", exc_info=True)
        return JsonResponse({
            'success': False,
            'message': f'应用草稿失败: {str(e)}'
        }, status=500)
