import argparse
from daphne.management.commands.runserver import Command as DaphneCommand
from asgi_autoreload import AutoreloadMiddleware


class Command(DaphneCommand):
    help = "Run Daphne with ASGI autoreload browser injection"

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            "--watch",
            nargs="*",
            default=["."],
            dest="watch_paths",
            help="Paths to watch for changes (default: .)",
        )
        parser.add_argument(
            "--exclude",
            nargs="*",
            default=[],
            dest="exclude_paths",
            help="Paths to exclude from watching.",
        )
        parser.add_argument(
            "build_cmd",
            nargs=argparse.REMAINDER,
            help="Optional build command to run on startup and on each change (after --).",
        )

    def get_application(self, options):
        app = super().get_application(options)
        watch_paths = options.get("watch_paths") or ["."]
        build_cmd = options.get("build_cmd") or []
        # argparse REMAINDER includes the leading "--" separator if present
        if build_cmd and build_cmd[0] == "--":
            build_cmd = build_cmd[1:]
        exclude_paths = options.get("exclude_paths") or []
        return AutoreloadMiddleware(
            app,
            watch_paths=watch_paths,
            build_command=build_cmd or None,
            exclude_paths=exclude_paths or None,
        )
