import json
import time
import random
from datetime import datetime
import threading
from config_center import CONFIG

class ActivityManager:
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
        return cls._instance

    def _get_config(self):
        """实时从 ConfigCenter 获取活动配置"""
        return CONFIG.get('activities', {})

    def get_all_activities(self):
        """返回所有活动配置"""
        return self._get_config()

    def get_activity(self, activity_id):
        config = self._get_config()
        return config.get(activity_id)

    def is_active(self, activity_id):
        act = self.get_activity(activity_id)
        if not act:
            return False
        if not act.get('enabled', False):
            return False
        now = datetime.now()
        start_str = act.get('start_time')
        end_str = act.get('end_time')
        if start_str:
            try:
                start = datetime.strptime(start_str, '%Y-%m-%d %H:%M:%S')
                if now < start:
                    return False
            except ValueError:
                # 时间格式错误时认为活动无效
                return False
        if end_str:
            try:
                end = datetime.strptime(end_str, '%Y-%m-%d %H:%M:%S')
                if now > end:
                    return False
            except ValueError:
                return False
        return True

    def get_activity_item(self, activity_id):
        act = self.get_activity(activity_id)
        if act and act.get('type') == 'drop_and_use':
            return act.get('item')
        return None

    def get_rewards(self, activity_id):
        act = self.get_activity(activity_id)
        return act.get('rewards', []) if act else []

    def update_activity_config(self, activity_id, updates):
        raise NotImplementedError("动态修改活动配置暂未实现")

activity_manager = ActivityManager()