import json
import os
from datetime import datetime, timedelta
from django.conf import settings
from filelock import FileLock

DRAFTS_PATH = os.path.join(settings.BASE_DIR, 'apps/content/drafts')
DRAFTS_FILE = os.path.join(DRAFTS_PATH, 'drafts.json')
LOCK_FILE = os.path.join(DRAFTS_PATH, 'drafts.lock')


def ensure_dir():
    """确保存储目录存在"""
    if not os.path.exists(DRAFTS_PATH):
        os.makedirs(DRAFTS_PATH)


def read_drafts():
    """读取所有草稿数据"""
    ensure_dir()
    if not os.path.exists(DRAFTS_FILE):
        return {}
    with open(DRAFTS_FILE, 'r', encoding='utf-8') as f:
        try:
            return json.load(f)
        except json.JSONDecodeError:
            return {}


def write_drafts(data):
    """写入草稿数据"""
    ensure_dir()
    with open(DRAFTS_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)


def cleanup_expired(data, days=3):
    """清理过期草稿"""
    now = datetime.now()
    expired = now - timedelta(days=days)

    for model in list(data.keys()):
        for user_id in list(data[model].keys()):
            for obj_id in list(data[model][user_id].keys()):
                item = data[model][user_id][obj_id]
                if datetime.fromisoformat(item['timestamp']) < expired:
                    del data[model][user_id][obj_id]
            # 删除空用户节点
            if not data[model][user_id]:
                del data[model][user_id]
        # 删除空模型节点
        if not data[model]:
            del data[model]
    return data


def atomic_operation(func):
    """带文件锁的原子操作装饰器"""

    def wrapper(*args, **kwargs):
        with FileLock(LOCK_FILE):
            return func(*args, **kwargs)

    return wrapper
