# views.py
import os
import threading
import time

from apps.upgrade.core import (UPGRADE_JSON_PATH, _execute_upgrade,  # 文件操作工具类
                               lock_upgrade_file, read_upgrade_status,
                               write_upgrade_status)
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST


# 升级守护线程
def _upgrade_daemon_thread(version):
    try:
        # 初始化进度
        write_upgrade_status({
            "status":
            "pending",
            "progress":
            0,
            "log":
            f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 升级任务初始化",
            "created_at":
            time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "version":
            version,
        })

        # 执行核心升级逻辑
        _execute_upgrade()

    except Exception as e:
        # 错误处理
        with lock_upgrade_file() as data:
            data["status"] = "failed"
            data["log"] += f"\n[SYSTEM ERROR] {str(e)}"
            write_upgrade_status(data)


# 启动升级接口
@csrf_exempt
@require_POST
def start_upgrade(request):
    # 清理旧进度文件（如果需要保留历史可改为归档）
    try:
        os.remove(UPGRADE_JSON_PATH)
    except:
        pass
    version = request.POST.get('version', 'v1.0')
    # 启动异步线程
    threading.Thread(target=_upgrade_daemon_thread,
                     args=(version, ),
                     daemon=True).start()

    return JsonResponse({}, status=202)


# 获取进度接口
def get_progress(request):
    status_data = read_upgrade_status()
    if not status_data:
        return JsonResponse({"error": "没有进行中的升级任务"}, status=404)

    return JsonResponse({
        'status':
        status_data["status"],
        'percentage':
        status_data["progress"],
        'logs':
        status_data["log"].split('\n'),  # 返回最后10条日志
        'version':
        status_data["version"],
        'timestamp':
        time.mktime(
            time.strptime(status_data["created_at"], "%Y-%m-%dT%H:%M:%SZ"))
    })
