import json
import os
import hashlib

APP_DIR = os.path.join(os.path.expanduser("~"), "GiteaAnalyzer")
DB_FILE = os.path.join(APP_DIR, "users.json")


def _ensure_app_dir():
    os.makedirs(APP_DIR, exist_ok=True)


def load_users():
    _ensure_app_dir()
    if not os.path.exists(DB_FILE):
        return {}
    try:
        with open(DB_FILE, "r", encoding="utf-8") as file:
            return json.load(file)
    except Exception:
        return {}


def save_users(users):
    _ensure_app_dir()
    with open(DB_FILE, "w", encoding="utf-8") as file:
        json.dump(users, file, ensure_ascii=False, indent=4)


def hash_password(password):
    return hashlib.sha256(password.encode("utf-8")).hexdigest()


def register_user(login, password):
    users = load_users()
    if login in users:
        return False, "Такой пользователь уже существует"
    users[login] = {
        "password": hash_password(password),
        "repositories": []
    }
    save_users(users)
    return True, "Профиль создан"


def check_user(login, password):
    users = load_users()
    user = users.get(login)
    if not user:
        return False
    return user.get("password") == hash_password(password)


def get_repositories(login):
    users = load_users()
    return users.get(login, {}).get("repositories", [])


def add_repository(login, repo_link):
    users = load_users()
    repos = users[login].setdefault("repositories", [])
    if repo_link not in repos:
        repos.append(repo_link)
        save_users(users)
        return True
    return False


def delete_repository(login, repo_link):
    users = load_users()
    repos = users[login].setdefault("repositories", [])
    if repo_link in repos:
        repos.remove(repo_link)
        save_users(users)
        return True
    return False
