import json
import os
import hashlib

DATA_FILE = "users_data.json"


def _load():
    if not os.path.exists(DATA_FILE):
        return {"users": {}}
    try:
        with open(DATA_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return {"users": {}}


def _save(data):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


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


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


def check_user(login, password):
    data = _load()
    user = data["users"].get(login)
    if not user:
        return False
    return user.get("password") == _hash_password(password)


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


def add_repository(login, link):
    data = _load()
    repos = data["users"].setdefault(login, {"password": "", "repositories": []}).setdefault("repositories", [])
    if link in repos:
        return False
    repos.append(link)
    _save(data)
    return True


def delete_repository(login, link):
    data = _load()
    repos = data["users"].get(login, {}).get("repositories", [])
    if link in repos:
        repos.remove(link)
        _save(data)
        return True
    return False
