from __future__ import annotations

import argparse
import json

from unuforge.runtime.host import load_host


def register(subparsers: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
    actions_parser = subparsers.add_parser("actions")
    actions_subparsers = actions_parser.add_subparsers(dest="actions_command", required=True)

    run_parser = actions_subparsers.add_parser("run")
    run_parser.add_argument("action_name", help="preset-backed deployment action to run")
    run_parser.add_argument("--preset", required=True, help="release preset JSON path")
    run_parser.add_argument("--host-adapter", required=True, help="python module path exporting HOST")
    run_parser.add_argument("--dry-run", action="store_true", help="print resolved execution without running")
    run_parser.add_argument("--json", action="store_true", help="emit structured output for dry-run mode")
    run_parser.set_defaults(handler=_handle_run)


def _normalize_passthrough_args(raw: list[str]) -> list[str]:
    if raw and raw[0] == "--":
        return raw[1:]
    return raw


def _handle_run(args: argparse.Namespace) -> int:
    passthrough_args = _normalize_passthrough_args(list(getattr(args, "passthrough_args", [])))
    host = load_host(args.host_adapter)
    execution = host.build_action_execution(args.preset, args.action_name, passthrough_args)

    if args.json:
        if not args.dry_run:
            raise ValueError("--json is only supported with --dry-run for action commands")
        print(json.dumps(execution, ensure_ascii=False))
        return 0

    if args.dry_run:
        print(" ".join(execution["command"]))
        return 0

    return host.run_action(args.preset, args.action_name, passthrough_args)
