import importlib.metadata
import sys
from pathlib import Path


_SPINNER_MESSAGES = {
    "init": "Initializing project",
    "init-elasticsearch": "Initializing Elasticsearch project",
    "add-tool": "Creating tool",
    "validate": "Validating configuration",
    "activate-plugin": "Activating plugin",
}


def _get_version() -> str:
    try:
        return importlib.metadata.version("smf-mcp")
    except importlib.metadata.PackageNotFoundError:
        return "unknown"


def _print_version() -> None:
    prog = Path(sys.argv[0]).name or "smf"
    print(f"{prog} {_get_version()}")


def main() -> int:
    argv = sys.argv[1:]
    if "--version" in argv:
        _print_version()
        return 0

    from smf.cli.parser import build_parser

    parser = build_parser(_get_version())
    args = parser.parse_args(argv)

    if not getattr(args, "func", None):
        parser.print_help()
        return 1

    message = _SPINNER_MESSAGES.get(getattr(args, "command", ""))
    if message:
        from contextlib import redirect_stdout
        from io import StringIO

        from smf.cli.spinner import Spinner

        buffer = StringIO()
        with Spinner(message, min_duration=0.3):
            with redirect_stdout(buffer):
                result = args.func(args)
        output = buffer.getvalue()
        if output:
            sys.stdout.write(output)
            sys.stdout.flush()
        return result

    return args.func(args)


if __name__ == "__main__":
    raise SystemExit(main())
