from github import Github
from .utils import get_logger, to_path, Path, exec_shell
from .config import GitConfig, load_pypi_creds
from .classes import PylibConfig, get_metadata_template
from typing import Dict

logger = get_logger()

class PylibClient:
    def __init__(self, github_token: str = None, pyirc_path: str = '~/.pypirc'):
        self.github_token = github_token or GitConfig.token
        self.pyirc = load_pypi_creds(pyirc_path)
        self.github = Github(login_or_token=self.github_token)
        self.cfg: PylibConfig = None
    
    def init_cfg(self, config_file: str = None, project_name: str = None, project_dir: str = None, *args, **kwargs):
        self.cfg = PylibConfig(github=self.github, github_token = self.github_token, config_file = config_file, project_name = project_name, project_dir = project_dir, *args, **kwargs)
    
    def init(self, project_dir: str = None, name: str = None, repo_user: str = None, private: bool = True, overwrite: bool = False, **kwargs):
        working_dir = to_path(project_dir) if project_dir else Path.cwd()
        if not name: name = working_dir.stem
        elif name not in working_dir.as_posix(): working_dir.joinpath(name)
        working_dir.mkdir(exist_ok=True)
        tmpl_file = working_dir.joinpath('metadata.yaml')
        if tmpl_file.exists() and not overwrite: raise ValueError(f'{tmpl_file.as_posix()} exists but overwrite is not selected')
        tmpl = get_metadata_template(github = self.github, name = name, repo_user = repo_user, private = private, **kwargs)
        logger.info(f'Writing Metadata template to {tmpl_file.as_posix()}')
        tmpl = "## Autogenerated by Pylibup\n\n" + tmpl
        tmpl_file.write_text(tmpl)
        #logger.info
        #logger.info(tmpl)

    def build(self, config_file: str = None, project_name: str = None, project_dir: str = None, commit_msg: str = 'Initialize', overwrite: bool = False, auto_publish: bool = False, *args, **kwargs):
        self.init_cfg(config_file= config_file, project_name = project_name, project_dir = project_dir, *args, **kwargs)
        self.cfg.build(commit_msg= commit_msg, overwrite= overwrite, auto_publish= auto_publish, *args, **kwargs)
        if auto_publish:
            extra_secrets = {}
            if self.cfg.config.needs_ipyirc:
                extra_secrets['PYPI_API_TOKEN'] = self.pyirc.get('pypi')
            self.create_secrets(extra_secrets)

    def create_secrets(self, extra_secrets: Dict[str, str] = {}):
        if not self.cfg: return
        assert self.cfg.repo_exists, 'Repo has not been created yet'
        repo = self.github.get_repo(self.cfg.config.repo_path)
        secrets = self.cfg.config.get_secrets()
        if secrets:
            for key, value in secrets.items():
                rez = repo.create_secret(secret_name = key, unencrypted_value = value)
                logger.info(f'Created Secret: {key} = {rez}')
        if extra_secrets:
            for key, value in extra_secrets.items():
                rez = repo.create_secret(secret_name = key, unencrypted_value = value)
                logger.info(f'Created Secret: {key} = {rez}')

    def publish(self, commit_msg: str = "Initialize", config_file: str = None, project_name: str = None, project_dir: str = None, *args, **kwargs):
        self.init_cfg(config_file= config_file, project_name = project_name, project_dir = project_dir, *args, **kwargs)
        self.cfg.publish_repo(commit_msg = commit_msg)



    









