"""
Usernames management service: loads from backend/static/userslist.json and exposes functions to get/add/delete usernames.
"""
import os
import json
from typing import List, Dict

USERS_FILE = os.path.join(os.path.dirname(__file__), '..', 'static', 'userslist.json')


def load_usernames() -> List[str]:
    try:
        with open(USERS_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception:
        return []


def save_usernames(usernames: List[str]) -> bool:
    try:
        with open(USERS_FILE, 'w', encoding='utf-8') as f:
            json.dump(usernames, f, ensure_ascii=False, indent=4)
        return True
    except Exception:
        return False


def get_usernames() -> Dict[str, object]:
    try:
        names = load_usernames()
        return {"success": True, "usernames": names}
    except Exception as e:
        return {"success": False, "message": str(e)}


def add_username(new_username: str) -> Dict[str, object]:
    new_username = new_username.strip()
    if not new_username:
        return {"success": False, "message": "Empty username"}
    names = load_usernames()
    if new_username in names:
        return {"success": False, "message": "Already exists", "usernames": names}
    names.append(new_username)
    names.sort()
    ok = save_usernames(names)
    if ok:
        return {"success": True, "message": "Added", "usernames": names}
    return {"success": False, "message": "Could not save"}


def delete_username(username: str) -> Dict[str, object]:
    username = username.strip()
    names = load_usernames()
    if username not in names:
        return {"success": False, "message": "Not found", "usernames": names}
    names.remove(username)
    ok = save_usernames(names)
    if ok:
        return {"success": True, "message": "Deleted", "usernames": names}
    return {"success": False, "message": "Could not save"}