import os

from frostfs_testlib.cli.frostfs_cli.cli import FrostfsCli
from frostfs_testlib.storage.dataclasses import ape
from frostfs_testlib.utils import string_utils


def create_bearer_token(frostfs_cli: FrostfsCli, directory: str, cid: str, rule: ape.Rule, endpoint: str) -> str:
    chain_file = os.path.join(directory, string_utils.unique_name("chain-", ".json"))
    bearer_token_file = os.path.join(directory, string_utils.unique_name("bt-", ".json"))
    signed_bearer_token_file = os.path.join(directory, string_utils.unique_name("bt-sign-", ".json"))

    frostfs_cli.bearer.generate_ape_override(rule.chain_id, rule=rule.as_string(), cid=cid, output=chain_file)
    frostfs_cli.bearer.create(endpoint, bearer_token_file, issued_at=1, expire_at=9999, ape=chain_file)
    frostfs_cli.util.sign_bearer_token(bearer_token_file, signed_bearer_token_file)

    return signed_bearer_token_file