"""
Entrypoint for calling Evennia as a module, with

    python -m evennia  (linux/unix)
    py -m evennia  (windows)

Notably, this should work also if evennia is installed with pip but
the executable is not on the path (so the plain `evennia` command
doesn't work).

For Windows, this will try to inject the evennia launcher into the executable path
to make the `evennia` command available.

"""

import os
import sys

from .server.evennia_launcher import main

if os.name == "nt":
    # we are on windows; we aim to place the executable in the
    # same place as the python file (for a virtualenv, this
    # would be the virtualenv's Scripts\ folder).
    binpath = os.path.join(sys.prefix, os.path.dirname(sys.executable))
    pyscript = """# auto-generated by py -m evennia (__main__.py)
import os
import sys
from evennia.server.evennia_launcher import main
sys.path.insert(0, os.path.abspath(os.getcwd()))
sys.path.insert(0, os.path.join(sys.prefix, "Lib", "site-packages"))
main()
"""
    pyscript_path = os.path.join(binpath, "evennia_launcher.py")

    batfile = f'@"{sys.executable}" "{pyscript_path}" %*'
    batfile_path = os.path.join(binpath, "evennia.bat")

    if not os.path.exists(pyscript_path):
        try:
            with open(pyscript_path, "w") as fil:
                fil.write(pyscript)
                print(f"... Created launcher {pyscript_path}.")
        except FileNotFoundError:
            print("Failed to add evennia_launcher.py to {pyscript_path}.")
    if not os.path.exists(batfile_path):
        try:
            with open(batfile_path, "w") as fil:
                fil.write(batfile)
                print(f"... Created batfile {batfile_path}.")
        except FileNotFoundError:
            print("Failed to add evennia.bat to {batfile_path}.")

# forward to the evennia launcher itself
main()
