# utils/storage.py

import json
import os
import datetime
from utils.constants import DATA_FILE, EVENTS_FILE, LAST_IDS_FILE

# 💾 Загрузка пользовательских данных (XP, минуты, уровень)
def load_user_data() -> dict:
    if not os.path.exists(DATA_FILE):
        return {}

    try:
        with open(DATA_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except json.JSONDecodeError:
        print("⚠️ Ошибка чтения user_data.json")
        return {}

# 💾 Сохранение пользовательских данных
def save_user_data(data: dict):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

# 📥 Загрузка событий (ивентов)
def load_event_tasks() -> dict:
    if not os.path.exists(EVENTS_FILE):
        return {}

    try:
        with open(EVENTS_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)

            for event_id, value in data.items():
                time_str = value["event"]["start_time"]
                dt = datetime.datetime.fromisoformat(time_str)

                # Если время без tzinfo, добавляем московскую зону
                if dt.tzinfo is None:
                    dt = dt.replace(tzinfo=MOSCOW_TZ)

                value["event"]["start_time"] = dt

            return data

    except Exception as e:
        print(f"❌ Ошибка при загрузке {EVENTS_FILE}: {e}")
        return {}

# 💾 Сохранение событий
def save_event_tasks(event_tasks: dict):
    to_save = {}
    for event_id, value in event_tasks.items():
        to_save[event_id] = {
            "event": {
                "name": value["event"]["name"],
                "start_time": value["event"]["start_time"].isoformat()
            },
            "votes": value["votes"],
            "poll_msg_id": value["poll_msg_id"]
        }
    with open(EVENTS_FILE, "w", encoding="utf-8") as f:
        json.dump(to_save, f, ensure_ascii=False, indent=2)

# 📥 Загрузка RSS-ID
def load_last_ids() -> set:
    if not os.path.exists(LAST_IDS_FILE):
        return set()

    try:
        with open(LAST_IDS_FILE, "r", encoding="utf-8") as f:
            return set(json.load(f))
    except Exception as e:
        print(f"❌ Ошибка чтения {LAST_IDS_FILE}: {e}")
        return set()

# 💾 Сохранение RSS-ID
def save_last_ids(ids: set):
    with open(LAST_IDS_FILE, "w", encoding="utf-8") as f:
        json.dump(list(ids), f, ensure_ascii=False, indent=2)
