"""Interactive entry point, contains main pypackage runtime logic."""


import os
import sys
import json
import setuptools
from datetime import datetime

from .cmdline import get_options
from .config import get_config
from .configure import set_value_in_config
from .configure import run_interactive_setup
from .constants import HELP
from .constants import META_NAME
from .constants import VERSION
from .context import SetupContext
from .context import ManifestContext
from .guessing import perform_guesswork


def pypackage_setup(setup_py_commands=None, options=None, additional=""):
    """Interactivly configure and run setuptools from static metadata.

    Used as the main entry point for all pypkg-* entry points except for setup

    Args:
        setup_py_commands: a list of string commands to run with setup.py
        options: the Options object from cmdline already initialized or None
        help: string additional infomation to include in help for this command
    """

    options = options or get_options()
    if options.help:
        raise SystemExit(HELP.format(additional="\n".join([
            line.replace("    ", "", 1).rstrip() for
            line in additional.splitlines()
        ])))
    elif options.version:
        raise SystemExit(VERSION)

    config = get_config()
    starting_metadata = config._metadata

    if not options.no_guess:
        perform_guesswork(config, options)

    # enter interactive setup if requested
    if options.interactive:
        run_interactive_setup(config, options)
    elif options.re_classify:
        set_value_in_config("classifiers", config, config._KEYS)

    if starting_metadata != config._metadata and config._metadata:
        banner = "# {} generated by `{}{}{}` at {} UTC\n".format(
            META_NAME,
            os.path.basename(sys.argv[0]),
            " " * int(len(sys.argv) > 1),
            " ".join(sys.argv[1:]),
            datetime.utcnow().isoformat().split(".")[0],
        )
        with open(META_NAME, "w") as openfile:
            openfile.write(banner + json.dumps(config._metadata, indent=4))

    kwargs = config._as_kwargs

    with ManifestContext(config, options):   # write the MANIFEST.in
        with SetupContext(config, options):  # write the setup.py
            if setup_py_commands:
                # use setuptools to build/install/test/whatever us directly
                sys.argv = ["setup.py"]
                sys.argv.extend(setup_py_commands)
                setuptools.setup(**kwargs)
            else:
                if options.interactive:
                    print(" setup.py ".center(40, "~"))
                print(config)
