import re
from typing import Optional
from worklib.auth_as_employer import get_access_token
import os
class NoTokenException(Exception):
    def __init__(self, tag):
        super().__init__(f"User {tag} does not have access token")


class AdminData:
    def __init__(self, tag):
        self.tag = tag
        self.username: Optional[str] = None
        self.access_token: Optional[str] = None
        self.refresh_token: Optional[str] = None
        self.profile_id: Optional[str] = None
        self.phone_number: Optional[str] = None
        self.account_id: Optional[str] = None


class UserManager:
    def __init__(self):
        self._users = {}
        self.last_user_tag = 0

    def get_or_create_user(self, user_tag) -> AdminData:
        user_id = self.str_to_user_tag(user_tag)
        if user_id not in self._users:
            self._users[user_id] = AdminData(user_id)
        return self._users[user_id]

    def str_to_user_tag(self, user):
        if user == "tester":
            return 0
        if user == "he":
            return self.last_user_tag or 0
        user_id = int(re.sub("[^0-9]", "", str(user)) or 0)
        self.last_user_tag = user_id
        return user_id

    def get_user_tags(self):
        return [user.tag for user in self._users.values()]

    def delete(self, user_tag):
        user_id = self.str_to_user_tag(user_tag)
        del self._users[user_id]

    def delete_user_by_username(self, username):
        for user_tag in list(self._users.keys()):
            if self._users[user_tag].username == username:
                del self._users[user_tag]
                return

    @property
    def users(self):
        return self._users.copy()


user_manager = UserManager()


def get_or_create_user(user_tag) -> AdminData:
    return user_manager.get_or_create_user(user_tag)

def get_access_token_from_env():
    # Берём значения из env, чтобы не хардкодить в тестах.
    username = os.getenv("AUTH_USERNAME", "+79214400842")
    password = os.getenv("AUTH_PASSWORD", "stepan")
    grant_type = os.getenv("AUTH_GRANT_TYPE", "password")

    token = get_access_token(username=username, password=password, grant_type=grant_type)
    access_token = token
    return access_token

    # Храним в простом менеджере, чтобы можно было расширять сценарии.
    get_or_create_user("tester").access_token = access_token