#!/usr/bin/env python3

import logging
import os
import sys
import misc

def show_help():
    print(
        f"""usage:
          {sys.argv[0]}: start a build server
          {sys.argv[0]} serve: start a build server
          {sys.argv[0]} config: bind xcworkspace and generate a buildServer.json to current dir
          {sys.argv[0]} parse: xcode log subcommand. call parse -h to see more help
          {sys.argv[0]} postaction: dump a xcode post build bash script to sync flags to .compile(usage: `{sys.argv[0]} postaction | bash &` in xcode post build bash script)
          {sys.argv[0]} [-h|--help]: show help

          SPECIAL ENVIRONMENT VARIABLE:
            SOURCEKIT_LOGGING=3: enable detail debug log
            XBS_LOGPATH: set log path. default is `:stderr`. use `:null` to disable log
            XBS_FEAT_NEWFILE=1: enable auto new file hack by infer flags from same dir files.., default true
          """
    )
    exit(0)

def show_debug_help():
    print(
        f"""usage:
          {sys.argv[0]} debug print-xclog <xcactivitylog_path>*: print xcactivitylog at path
          """
    )
    exit(0)

def serve():
    import server
    server.serve()

def setup_root_logger():
    level = os.environ.get("SOURCEKIT_LOGGING")
    xbs_debug = ((level is not None and int(level) >= 1) or os.environ.get("XBS_DEBUG") == "1"
        or os.environ.get("XBSDEBUG") == "1") # compatible, remove in future
    level = logging.DEBUG if xbs_debug else logging.INFO

    xbs_logpath = os.environ.get("XBS_LOGPATH")

    if xbs_logpath:
        if xbs_logpath == ":null":
            logging.basicConfig(handlers=[logging.NullHandler()], level=level)
        elif xbs_logpath == ":stderr":
            logging.basicConfig(stream=sys.stderr, level=level)
        else:
            logging.basicConfig(filename=xbs_logpath, level=level)
    else:
        logging.basicConfig(stream=sys.stderr, level=level)

    if xbs_debug:
        logging.info(f"# xcode build server {misc.VERSION} with python {sys.version}]")


def main():
    setup_root_logger()

    if len(sys.argv) > 1:

        if "-h" == sys.argv[1] or "--help" == sys.argv[1]:
            show_help()

        def subcommand_argv():
            argv = sys.argv.copy()
            argv[0] = f"{argv[0]} {argv[1]}"
            del argv[1]
            return argv

        if sys.argv[1] == "config":
            from config.cmd import main

            main(subcommand_argv())
        elif sys.argv[1] == "parse":
            import xclog_parser

            xclog_parser.main(subcommand_argv())
        elif sys.argv[1] == "postaction":
            sys.stdout.write(
                rf"""
            bash "{os.path.abspath(os.path.join(os.path.realpath(__file__), "..", "post_action.bash"))}"
            """
            )
        elif sys.argv[1] == "serve":
            serve()
        elif sys.argv[1] == "debug":

            if sys.argv[2] == "print-xclog":
                import xcactivitylog
                for path in sys.argv[3:]:
                    print(f"extract xcactivitylog at {path}")
                    for l in xcactivitylog.extract_compile_log(path):
                        print(l)
            elif sys.argv[2] == "build":
                import subprocess
                code = subprocess.call(["osascript", "-l", "JavaScript", misc.bundle_path("xcode/build.js"), *sys.argv[3:]])
                exit(code)
            else:
                show_debug_help()
        else:
            show_help()
    else:
        # else serve as build server, and wait json reqest
        serve()


if __name__ == "__main__":
    # print(sys.path)
    # sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    main()
