#!/usr/bin/env python3
#
# gentags - for use in vim
# NOTE: this file lives in both ~/bin and ~/.vim/tool.

import os.path
import shutil
import subprocess
import sys
import typing as T
from pathlib import Path

VERSION = "0.2.0"


def split(args_str: str) -> list[str]:
    return args_str.strip().splitlines()


# From `vimrc`.
ctags_bins = []
# Prefer Universal Ctags (the maintained fork of Exuberant Ctags).
ctags_bins += ["ctags-universal"]
ctags_bins += ["universal-ctags"]

# Remaining options taken from `tagbar/autoload/tagbar.vim`:
ctags_bins += ["ctags-exuberant"]  # Debian
ctags_bins += ["exuberant-ctags"]
ctags_bins += ["exctags"]  # FreeBSD, NetBSD
ctags_bins += ["/usr/local/bin/ctags"]  # Homebrew
ctags_bins += ["/opt/local/bin/ctags"]  # Macports
ctags_bins += ["ectags"]  # OpenBSD
ctags_bins += ["ctags"]
ctags_bins += ["ctags.exe"]
ctags_bins += ["tags"]

ctags_std_args = split(
    r"""
--c-kinds=+px
--c++-kinds=+px
--fields=+iaS
--extra=+qf
""",
)

ctags_stdx_args = split(
    r"""
--exclude=export
--exclude=build
--exclude=builddir
--exclude=bindir
--exclude=pkgexp
--exclude=Sphere
--exclude=target
--exclude=venv
--exclude=dist
--exclude=.pytest_cache
--exclude=.cache
""",
)

# for use in vim: with ctags-exuberant only
# taken from `ctags/rust.ctags` in https://github.com/rust-lang/rust.vim.
ctags_rust_args = split(
    r"""
--langdef=Rust
--langmap=Rust:.rs
--regex-Rust=/^[ \t]*(#\[[^\]]\][ \t]*)*(pub[ \t]+)?(extern[ \t]+)?("[^"]+"[ \t]+)?(unsafe[ \t]+)?fn[ \t]+([a-zA-Z0-9_]+)/\6/f,functions,function definitions/
--regex-Rust=/^[ \t]*(pub[ \t]+)?type[ \t]+([a-zA-Z0-9_]+)/\2/T,types,type definitions/
--regex-Rust=/^[ \t]*(pub[ \t]+)?enum[ \t]+([a-zA-Z0-9_]+)/\2/g,enum,enumeration names/
--regex-Rust=/^[ \t]*(pub[ \t]+)?struct[ \t]+([a-zA-Z0-9_]+)/\2/s,structure names/
--regex-Rust=/^[ \t]*(pub[ \t]+)?mod[ \t]+([a-zA-Z0-9_]+)/\2/m,modules,module names/
--regex-Rust=/^[ \t]*(pub[ \t]+)?(static|const)[ \t]+([a-zA-Z0-9_]+)/\3/c,consts,static constants/
--regex-Rust=/^[ \t]*(pub[ \t]+)?trait[ \t]+([a-zA-Z0-9_]+)/\2/t,traits,traits/
--regex-Rust=/^[ \t]*(pub[ \t]+)?impl([ \t\n]*<[^>]*>)?[ \t]+(([a-zA-Z0-9_:]+)[ \t]*(<[^>]*>)?[ \t]+(for)[ \t]+)?([a-zA-Z0-9_]+)/\4 \6 \7/i,impls,trait implementations/
--regex-Rust=/^[ \t]*macro_rules![ \t]+([a-zA-Z0-9_]+)/\1/d,macros,macro definitions/
""",
)


def probe_ctags_bin() -> str:
    for name in ctags_bins:
        if shutil.which(name):
            return name
    return "ctags"


def is_universal_ctags(ctags_bin: str) -> bool:
    output = subprocess.check_output([ctags_bin, "--version"])
    return b"universal ctags" in output.lower()


def launder_args(args: list[str], *, is_universal: bool) -> T.Generator[str, None, None]:
    extras = "--extras" if is_universal else "--extra"
    for arg in args:
        for prefix in ["--extras", "--extra"]:
            if arg.startswith(prefix):
                arg = extras + arg[len(prefix) :]
                break
        yield arg


# (`ttype`, `tag_path_suffix`, `tag_line`)
Item = tuple[bytes, bytes, bytes]


def sort_tags_file(tags_path_in: Path, tags_path_out: Path) -> None:
    with open(tags_path_in, "rb") as tags_in, open(tags_path_out, "wb") as tags_out:
        c_suffixes = set(
            b"""
            .c .h .cpp .cxx .c++ .hh .hxx .hpp .ipp .moc .tcc .inl
        """.split(),
        )
        group: list[Item] = []
        cur_tag_name = b""

        def item_key(item: Item) -> int:
            ttype, tag_path_suffix, _tag_line = item
            if ttype == b"p" and tag_path_suffix in c_suffixes:
                # Move C function prototypes later in the `tags` file.
                return 1

            # Leave other items alone.
            return 0

        def flush() -> None:
            if len(group) > 1:
                group.sort(key=item_key)
            for _ttype, _tag_path_suffix, tag_line in group:
                tags_out.write(tag_line)
            group.clear()

        def pass_bline(tag_line) -> None:
            flush()
            tags_out.write(tag_line)

        for tag_line in tags_in:
            if tag_line.startswith(b"!_"):
                pass_bline(tag_line)
                continue
            parts = tag_line.split(b';"\t')
            if len(parts) != 2:
                pass_bline(tag_line)
                continue

            fields0 = parts[0].split(b"\t")
            if len(fields0) < 2:
                pass_bline(tag_line)
                continue

            tag_name = fields0[0]
            tag_path_suffix = os.path.splitext(fields0[1])[1]
            ttype = parts[1].split(b"\t")[0]
            if tag_name != cur_tag_name:
                flush()
                cur_tag_name = tag_name
            group.append((ttype, tag_path_suffix, tag_line))

        flush()


class Config:
    def __init__(self) -> None:
        self.ctags_bin = probe_ctags_bin()
        self.show = False
        self.show_help = False
        self.show_gentags_help = False
        self.is_universal = True
        self.std = False
        self.stdx = False
        self.rg = False
        self.sort_tags = False
        self.args: list[str] = []


def help_gentags() -> None:
    print(
        f"""\
Help for gentags version {VERSION}
  --help-gentags            Help on gentags
  --show                    Show args for ctags
  --ctags CTAGS             Use CTAGS executable
  --std                     Use "standard" ctags arguments
  --stdx                    Use "standard" ctags `--exclude` paths
  --rg                      Use `rg --files | ctags -L -`
  --sort-tags               Sort `tags` file after generation

`--sort-tags` moves C function prototype tags later in the `tags` file so
function definitions take precedence.  Currently, this assumes the generated
tags file is the default `tags`.

With no arguments, `--std --stdx --sort-tags` is implied; additionally, use
`--rg` if have `.gitignore/.ignore` files and `rg` is detected, and
`--recursive` otherwise.
""",
    )


def required_arg(arg: str, args: list[str]) -> str:
    if args:
        return args.pop(0)
    print(f"Missing required arg for {arg}")
    sys.exit()


def parse_args(args: list[str]) -> Config:
    config = Config()
    args = args[:]
    while args:
        arg = args.pop(0)
        if arg == "--help":
            config.show_help = True
        elif arg == "--help-gentags":
            config.show_gentags_help = True
        elif arg == "--show":
            config.show = True
        elif arg == "--ctags":
            config.ctags_bin = required_arg(arg, args)
        elif arg == "--std":
            config.std = True
        elif arg == "--stdx":
            config.stdx = True
        elif arg == "--rg":
            config.rg = True
        elif arg == "--sort-tags":
            config.sort_tags = True
        else:
            config.args.append(arg)
    config.is_universal = is_universal_ctags(config.ctags_bin)
    return config


def main() -> None:
    args = sys.argv[1:]
    rg = shutil.which("rg")
    has_ignore = Path(".gitignore").exists() or Path(".ignore").exists()
    if args == [] or args == ["--show"]:
        args.extend(["--std", "--stdx", "--sort-tags"])
        if rg and has_ignore:
            args.append("--rg")
        else:
            args.append("--recurse")
    config = parse_args(args)

    if config.show_gentags_help:
        help_gentags()
        return

    if config.show_help:
        subprocess.run([config.ctags_bin, "--help"])
        print("Use --help-gentags for gentags help")
        return

    if config.stdx:
        config.args[:0] = ctags_stdx_args
    if config.std:
        if not config.is_universal:
            config.args[:0] = ctags_rust_args
        config.args[:0] = ctags_std_args
    if config.rg:
        config.args[:0] = ["-L", "-"]
        rg_cmd_args = ["rg", "--files"]
    else:
        rg_cmd_args = []

    # Launder args for Exuberant/Universal incompatibilities.
    config.args = list(launder_args(config.args, is_universal=config.is_universal))
    ctags_cmd_args = [config.ctags_bin] + config.args

    def sort_tags():
        if config.sort_tags:
            orig_tags_path = Path("tags")
            sorted_tags_path = Path("tags.sorted")
            sort_tags_file(orig_tags_path, sorted_tags_path)
            os.rename(sorted_tags_path, orig_tags_path)

    if config.show:
        pre = " ".join(rg_cmd_args) + " | " if rg_cmd_args else ""
        sep = " \\\n    "
        print(pre + sep.join(ctags_cmd_args))
    elif rg_cmd_args:
        rg_proc = subprocess.Popen(rg_cmd_args, stdout=subprocess.PIPE)
        assert rg_proc.stdout is not None
        subprocess.run(ctags_cmd_args, stdin=rg_proc.stdout)
        rg_proc.stdout.close()
        sort_tags()
    else:
        subprocess.run(ctags_cmd_args)
        sort_tags()


if __name__ == "__main__":
    main()
