#!/usr/bin/env python3
from build_aux.build_common import color
import build_aux.build_common as bc
import argparse
from pathlib import Path
import os

def main():
    parser = argparse.ArgumentParser(
        description="SysD Manager build tools",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument(
        "-d",
        "--allow_dirty",
        action="store_true",
        dest="allow_dirty",
        help="allow not commited file",
        default=False,
    )

    parser.add_argument(
        "action",
        choices=["version", "gschema", "clean-gschema"],
        help="actions to perform",
    )

    parser.add_argument(
        "-m", "--message", dest="message", help="Add a messge to the git command"
    )

    parser.add_argument(
        "-f",
        "--force",
        dest="force",
        action="store_true",
        help="Force tag to be able to move the tag to the moste recent commit",
    )

    args = parser.parse_args()

    match args.action:
        case "version":
            version(args.allow_dirty, args.message, args.force)
        case "gschema":
            gschema()
        case "clean-gschema":
            clean_gschema()


def version(allow_dirty: bool, message: str, force: bool):
    print(f"{color.CYAN}Create as git tag and push it{color.END}")

    if bc.is_repo_dirty() and not allow_dirty:
        print(f"repo dirty {color.BOLD}Exit{color.END}")
        exit()

    tag_name = bc.get_version_tag()

    print(f"Program version {color.BOLD}{version}{color.END}")
    print(f"Git tag {color.BOLD}{color.YELLOW}{tag_name}{color.END}")

    if not message:
        print(f'Message needed (-m "a message ...")')
        message = f'version {tag_name}'
        print(f'Message supplied (-m "{message}")')

    git_tag = ["git", "tag", "-m", f'"{message}"', tag_name]
    git_push = ["git", "push", "origin", "tag", tag_name]

    if force:
        git_tag.insert(2, "-f")
        git_push.insert(2, "-f")

    bc.cmd_run(git_tag)
    bc.cmd_run(git_push)


def gschema():

    home = Path.home()
    GLIB_SCHEMAS_DIR: str = ".local/share/glib-2.0/schemas/"
    GLIB_SCHEMAS_FILE: str = "data/schemas/io.github.plrigaux.sysd-manager.gschema.xml"

    out_dir = os.path.join(home, GLIB_SCHEMAS_DIR)

    bc.cmd_run(
        [
            "install",
            "-v",
            "-D",
            GLIB_SCHEMAS_FILE,
            "-t",
            out_dir,
        ]
    )

    bc.cmd_run(
        [
            "glib-compile-schemas",
            out_dir,
        ]
    )


def clean_gschema():
    bc.clean_gschema()


if __name__ == "__main__":
    main()
