# -*- coding: utf-8 -*-

"""
Package setup.

Set me up with `python setup.py bdist_wheel --universal`
"""
import io
import json
import os

from setuptools import setup

# Get long description from readme
with io.open("README.md", "rt", encoding="utf8") as readmefile:
    README = readmefile.read()

# Convert emojilib json file to python dictionary, so we don't have the parse
# penalty at runtime

# The dir where this file is located is relative to the root dir (where the
# tox.ini file is located). Our tox setup will inject an env variable with that
# path, because we do isolated tox builds in non-root folders eg when running in
# parallel
SETUP_RUN_DIR = os.environ.get("TOX_INI_DIR", os.path.dirname(__file__))


def get_gemoji_db_data(root_dir):
    """get a dictionary of emoji data from the gemoji database."""
    emoji_dict = {}

    # Load the gemoji database as a baseline
    with io.open(
        os.path.join(root_dir, "gemoji/db/emoji.json"),
        "rt",
        encoding="utf8",
    ) as gemoji_db:
        gemoji_db_data = json.load(gemoji_db)
    # create the dictionary of emojis, keyed by canonical name
    for emoji in gemoji_db_data:
        # the emoji canonical name; can contain spaces, replace with _
        name = "_".join(emoji["description"].split(" "))
        emoji_dict[name] = {
            # the unicode codepoint sequence itself
            "emoji": emoji["emoji"],
            # any aliases the gemoji lib provides
            "aliases": tuple(emoji["aliases"]),
        }

    return emoji_dict


def generate_emoji_db(root_dir, outfile="emoji_fzf/emoji_fzf_emojilib.py"):
    """generate the emoji_fzf_emojilib.py file from the gemoji and emojilib databases."""

    emoji_dict = {}
    emoji_dict.update(get_gemoji_db_data(root_dir))

    # merge the aliases from the emojilib database
    # 1. load the json
    with io.open(
        os.path.join(root_dir, "emojilib/dist/emoji-en-US.json"),
        "rt",
        encoding="utf8",
    ) as emojilib_db:
        emojilib_db_data = json.load(emojilib_db)
    # 2. dictionary, keyed by codepoint, of aliases
    emojilib_db_by_codepoint = {}
    for codepoint, aliases in emojilib_db_data.items():
        emojilib_db_by_codepoint[codepoint] = tuple(aliases)

    # 3. iterate over the gemoji dictionary, updating any common codepoint with the
    #    aliases in the emojilib dictionary. use set() to eliminate duplicates (no
    #    lexical de-duping tho)
    for key, val in emoji_dict.items():
        additional_aliases = emojilib_db_by_codepoint.pop(val["emoji"], tuple())
        # pylint: disable=unnecessary-dict-index-lookup
        emoji_dict[key]["aliases"] = tuple(set(val["aliases"] + additional_aliases))

    # 4. add in any emojilib entries that weren't in the gemoji database
    for codepoint, (name, *aliases) in emojilib_db_by_codepoint.items():
        # some of these have spaces, sub in '_' to make it work nicer with fzf
        # preview
        name = name.replace(" ", "_")
        emoji_dict[name] = {"emoji": codepoint, "aliases": tuple(aliases)}

    with open(outfile, "w", encoding="utf-8") as genfile:
        genfile.write(
            """# -*- coding: utf-8 -*-
\"\"\"
Emoji python alias file, autogenerated.
\"\"\"

"""
        )

        # Unfortunately this doesn't work; we end up with literals like '\\U0001f600' 😕
        # not suitable for printing alas. For now, just archive the py2 output,
        # which on both
        #
        # # we want the emojilib file to have the literal symbols represented as ascii
        # # literals with \u escape sequences, which we can safely use in python2 with
        # # codecs.getwriter('utf-8') to print the symbol. to make sure the emojilib
        # # is formatted correctly when the wheel is built with python3, use a little
        # # goofy logic.
        # import sys
        # if sys.version_info >= (3,):
        #     for key, val in EMOJI_DICT.items():
        #         EMOJI_DICT[key]["emoji"] = (
        #             val["emoji"].encode("ascii", "backslashreplace").decode("utf-8")
        #         )

        genfile.write("EMOJIS = {}".format(emoji_dict))


if __name__ == "__main__":
    generate_emoji_db(SETUP_RUN_DIR)

    setup(
        # I think using `-` instead of `_` is more user-friendly, but due to python
        # import directives not allowing `-`, keep everything consistent with `_`.
        name="emoji-fzf",
        version="0.8.0",
        description="Emoji searcher for use with fzf",
        author="Noah Pendleton",
        author_email="2538614+noahp@users.noreply.github.com",
        url="https://github.com/noahp/emoji-fzf",
        project_urls={
            "Code": "https://github.com/noahp/emoji-fzf",
            "Issue tracker": "https://github.com/noahp/emoji-fzf/issues",
        },
        long_description=README,
        long_description_content_type="text/markdown",
        install_requires=["click"],
        # using markdown as pypi description:
        # https://dustingram.com/articles/2018/03/16/markdown-descriptions-on-pypi
        setup_requires=["setuptools>=38.6.0", "wheel>=0.31.0", "twine>=1.11.0"],
        packages=["emoji_fzf"],
        entry_points={"console_scripts": ["emoji-fzf = emoji_fzf.emoji_fzf:cli"]},
        classifiers=[
            "License :: OSI Approved :: MIT License",
            "Programming Language :: Python :: 3.7",
            "Programming Language :: Python :: 3.8",
            "Programming Language :: Python :: 3.9",
            "Programming Language :: Python :: 3.10",
            "Programming Language :: Python :: 3.11",
            "Operating System :: OS Independent",
        ],
    )
