from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Dict

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from auditwalk.cli.registry import CommandRegistry


@dataclass(frozen=True)
class Invocation:
    noun: str
    verb: str
    args: Dict[str, Any]
    opts: Dict[str, Any]


def _dest_from_flags(flags):
    long_flags = [f for f in flags if f.startswith("--")]
    base = (long_flags[0] if long_flags else flags[0]).lstrip("-")
    return base.replace("-", "_")


def build_invocation_from_namespace(registry: "CommandRegistry", noun: str, verb: str, parsed: Dict[str, Any]) -> Invocation:
    spec = registry.get(noun, verb)

    arg_names = {a.name for a in spec.args}
    opt_dests = {_dest_from_flags(o.flags) for o in spec.opts}

    args: Dict[str, Any] = {}
    opts: Dict[str, Any] = {}
    for k, v in parsed.items():
        if k in arg_names:
            args[k] = v
        elif k in opt_dests:
            opts[k] = v
        else:
            opts[k] = v

    return Invocation(noun=noun, verb=verb, args=args, opts=opts)


def dispatch(registry: "CommandRegistry", inv: Invocation) -> int:
    spec = registry.get(inv.noun, inv.verb)
    return int(spec.handler(inv))
