import json
import pickle
import os
from pathlib import Path
import importlib.resources as pkg_resources

# -------------------------------------------------------------
# 1. Get user config directory
# -------------------------------------------------------------
def get_user_config_dir() -> Path:
	"""
	Return the path of user config directory.
	Windows: C:/Users/<name>/just_vbpe/
	Linux:   ~/just_vbpe/
	macOS:   ~/just_vbpe/
	"""
	home = Path.home()
	cfg_dir = home / "just_vbpe"
	cfg_dir.mkdir(parents=True, exist_ok=True)
	return cfg_dir

# -------------------------------------------------------------
# 2. Load/Save JSON
# -------------------------------------------------------------
def load_json_from_package(models_pkg, filename: str):
	with pkg_resources.open_text(models_pkg, filename, encoding="utf-8") as f:
		return json.load(f)

def save_json_to_user(data, filename="tokens.json"):
	file_path = get_user_config_dir() / filename
	with open(file_path, "w", encoding="utf-8") as f:
		json.dump(data, f, ensure_ascii=False, indent=2)
	return file_path

def load_json_from_user(filename="tokens.json"):
	file_path = get_user_config_dir() / filename
	if not file_path.exists():
		raise FileNotFoundError(f"File not found: {file_path}")
	with open(file_path, "r", encoding="utf-8") as f:
		return json.load(f)

# -------------------------------------------------------------
# 3. Load/Save Pickle
# -------------------------------------------------------------
def load_pickle_from_package(models_pkg, filename: str):
	with pkg_resources.open_binary(models_pkg, filename) as f:
		return pickle.load(f)

def save_pickle_to_user(data, filename="tokens.pkl"):
	file_path = get_user_config_dir() / filename
	with open(file_path, "wb") as f:
		pickle.dump(data, f)
	return file_path

def load_pickle_from_user(filename="tokens.pkl"):
	file_path = get_user_config_dir() / filename
	if not file_path.exists():
		raise FileNotFoundError(f"File not found: {file_path}")
	with open(file_path, "rb") as f:
		return pickle.load(f)