import datetime
from pathlib import Path

from django.conf import settings
from django.http import JsonResponse

LOG_DIR = Path(settings.STATIC_ROOT) / "shared/text_log"


def createLog(message, filename, max_lines=500):
    """
    通用日志写入函数
    :param filename: 日志文件名(如"ai_logs.txt")
    :param message: 日志内容
    :param max_lines: 最大保留行数(默认500)
    """
    LOG_DIR.mkdir(parents=True, exist_ok=True)
    log_file = LOG_DIR / filename

    timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    new_entry = f"{timestamp}：{message}\n"

    existing_lines = []
    try:
        with open(log_file, "a+", encoding="utf-8") as file:
            file.seek(0)
            existing_lines = file.readlines()
    except Exception as e:
        print(f"读取日志文件失败: {e}")

    all_lines = existing_lines + [new_entry]
    processed_lines = []
    for line in all_lines:
        if line.strip():
            processed_lines.append(line.strip())
        if len(processed_lines) >= max_lines:
            break

    try:
        with open(log_file, "w", encoding="utf-8") as file:
            file.write("\n".join(processed_lines))
    except Exception as e:
        print(f"写入日志文件失败: {e}")


def get_logs(request, filename, reverse=False):
    """
    通用日志读取API
    :param request: Django请求对象
    :param filename: 日志文件名(如"ai_logs.txt")
    :param reverse: 是否倒序排列(最新在前)
    :return: JsonResponse
    """
    log_file = LOG_DIR / filename

    if not log_file.exists():
        return JsonResponse({"error": "Log file not found"},
                            status=404,
                            json_dumps_params={'ensure_ascii': False})

    try:
        with open(log_file, 'r', encoding='utf-8') as f:
            logs = [line.strip() for line in f if line.strip()]
            if reverse:
                logs.reverse()
    except PermissionError:
        return JsonResponse({"error": "Permission denied"},
                            status=403,
                            json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({"error": f"Error reading file: {str(e)}"},
                            status=500,
                            json_dumps_params={'ensure_ascii': False})

    return JsonResponse({"logs": logs},
                        status=200,
                        safe=False,
                        json_dumps_params={
                            'ensure_ascii': False,
                            'indent': 2
                        })


ai_logs_filename = 'ai_article_logs.txt'


def createAIlog(message):
    createLog(message, ai_logs_filename)


def get_ai_logs(request):
    data = get_logs(request, ai_logs_filename)
    return data


article_update_status_filename = 'article_update_status.txt'


def create_article_update_status_log(message):
    createLog(message, article_update_status_filename)


def get_article_update_status_logs(request):
    data = get_logs(request, article_update_status_filename)
    return data
