"""nbstata kernel install script"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/15_install.ipynb.

# %% auto 0
__all__ = ['kernel_json', 'install_kernel_spec', 'create_conf_if_needed', 'main']

# %% ../nbs/15_install.ipynb 3
import argparse
import json
import os
import sys

from jupyter_client.kernelspec import KernelSpecManager
from IPython.utils.tempdir import TemporaryDirectory
from importlib import resources
from shutil import copyfile
from pathlib import Path
from textwrap import dedent
from fastcore.basics import IN_NOTEBOOK

# %% ../nbs/15_install.ipynb 5
kernel_json = {
    "argv": [sys.executable, "-m", "nbstata", "-f", "{connection_file}"],
    "display_name": "Stata (nbstata)",
    "language": "stata",
}

def install_kernel_spec(user=True, prefix=None):
    with TemporaryDirectory() as td:
        os.chmod(td, 0o755) # Starts off as 700, not user readable
        with open(os.path.join(td, 'kernel.json'), 'w') as f:
            json.dump(kernel_json, f, sort_keys=True)

        # Copy logo to tempdir to be installed with kernelspec
        logo_path = resources.files('nbstata').joinpath('logo-64x64.png')
        copyfile(logo_path, os.path.join(td, 'logo-64x64.png'))

        print('Installing Jupyter kernel spec')
        KernelSpecManager().install_kernel_spec(td, 'nbstata', user=user, prefix=prefix)

# %% ../nbs/15_install.ipynb 6
def _find_stata():
    # By avoiding an import of .config until we need it, we can
    # complete the installation process in virtual environments
    # without needing this submodule nor its downstream imports.
    from nbstata.config import find_dir_edition
    try:
        stata_dir, stata_ed = find_dir_edition()
    except OSError as err:
        stata_dir, stata_ed = "", ""
    return stata_dir, stata_ed

# %% ../nbs/15_install.ipynb 7
def _conf_default(stata_dir='', stata_ed=''):
    from nbstata.config import Config
    conf_default = dedent(
        f"""\
        [nbstata]
        stata_dir = {stata_dir}
        edition = {stata_ed}
        """
    )
    for key in Config.env.keys():
        if key not in {'stata_dir', 'edition'}:
            conf_default += f"{key} = {Config.env[key]}\n"
    return conf_default

# %% ../nbs/15_install.ipynb 8
def create_conf_if_needed(conf_path, conf_file_requested=True):
    """Create config file if requested or if Stata not found automatically"""
    if conf_path.is_file():
        if conf_file_requested:
            print("Configuration file already exists at:")
            print(str(conf_path))
        return
    stata_dir, stata_ed = _find_stata()
    if not stata_ed:
        msg = """\
            WARNING: Could not find Stata path.
            Please specify it manually in configuration file.
            """
        print(dedent(msg))
    if stata_ed and not conf_file_requested:
        return
    try:
        conf_dir = Path(os.path.dirname(conf_path))
        if not conf_dir.is_dir():
            os.makedirs(conf_dir)
        with conf_path.open('w') as f:
            f.write(_conf_default(stata_dir, stata_ed))
        print("Configuration file created at:")
        print(str(conf_path))
    except Exception as err:
        print(f"Attempt to create a configuration file at {str(conf_path)} failed.")
        raise(err)

# %% ../nbs/15_install.ipynb 10
def _is_root():
    try:
        return os.geteuid() == 0
    except AttributeError:
        return False # assume not an admin on non-Unix platforms

# %% ../nbs/15_install.ipynb 12
def _conf_path(user, prefix):
    from nbstata.config import old_user_config_path, xdg_user_config_path
    if user:
        alt_conf_path = old_user_config_path()
        if alt_conf_path.is_file():
            return alt_conf_path
        else:
            return xdg_user_config_path()
    else:
        return Path(os.path.join(prefix, 'etc/nbstata.conf'))

# %% ../nbs/15_install.ipynb 14
def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument('--user', action='store_true',
        help="Install to the per-user kernels registry. Default if not root.")
    ap.add_argument('--sys-prefix', action='store_true',
        help="Install to sys.prefix (e.g. a virtualenv or conda env)")
    ap.add_argument('--prefix',
        help="Install to the given prefix. "
             "Kernelspec will be installed in {PREFIX}/share/jupyter/kernels/")
    ap.add_argument('--conf-file', action='store_true',
        help="Create a configuration file.")
    args = ap.parse_args(argv)

    if args.sys_prefix:
        args.prefix = sys.prefix
    if not args.prefix and not _is_root():
        args.user = True

    install_kernel_spec(user=args.user, prefix=args.prefix)
    conf_path = _conf_path(user=args.user, prefix=sys.prefix)
    create_conf_if_needed(conf_path, conf_file_requested=args.conf_file)

# %% ../nbs/15_install.ipynb 15
#|eval: false
if __name__ == "__main__" and not IN_NOTEBOOK:
    main()
