from __future__ import annotations

import sys


def aiwaf_detect() -> None:
    try:
        from aiwaf.django.trainer import train
    except Exception as exc:
        sys.stderr.write(
            "aiwaf-detect requires Django integration. Install with:\n"
            "  pip install aiwaf[django]\n"
        )
        raise SystemExit(1) from exc

    train()


def main() -> None:
    """Top-level AIWAF CLI entrypoint.

    Supports both styles:
    - `aiwaf <command> ...` (unified default command set)
    - `aiwaf <framework> <command> ...` where framework is flask|fast|django
    """
    frameworks = {"django", "flask", "fast"}
    argv = list(sys.argv[1:])

    if argv and argv[0] in frameworks:
        framework = argv[0]
        framework_args = argv[1:]
    else:
        # Unified shorthand: route bare commands through the shared Fast/Flask CLI.
        framework = "fast"
        framework_args = argv

    if framework == "flask":
        from aiwaf.flask.cli import main as flask_main

        sys.argv = ["aiwaf flask"] + list(framework_args)
        flask_main()
        return
    if framework == "fast":
        from aiwaf.fast.cli import main as fast_main

        sys.argv = ["aiwaf fast"] + list(framework_args)
        fast_main()
        return
    if framework == "django":
        try:
            from django.core.management import execute_from_command_line
        except Exception as exc:
            sys.stderr.write(
                "aiwaf django requires Django integration. Install with:\n"
                "  pip install aiwaf[django]\n"
            )
            raise SystemExit(1) from exc

        if not framework_args:
            sys.stderr.write(
                "Usage: aiwaf django <management-command> [args]\n"
                "Example: aiwaf django aiwaf_list --all\n"
            )
            raise SystemExit(2)

        execute_from_command_line(["aiwaf django"] + list(framework_args))
        return


if __name__ == "__main__":
    main()
