from __future__ import annotations

import argparse
import json

from unuforge.runtime.host import load_host
from unuforge.runtime.presets import load_preset, preset_profile_names


def register(subparsers: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
    profiles_parser = subparsers.add_parser("profiles")
    profiles_subparsers = profiles_parser.add_subparsers(dest="profiles_command", required=True)

    list_parser = profiles_subparsers.add_parser("list")
    list_parser.add_argument("--preset", required=True, help="release preset JSON path")
    list_parser.add_argument("--json", action="store_true", help="emit structured output")
    list_parser.set_defaults(handler=_handle_list)

    run_parser = profiles_subparsers.add_parser("run")
    run_parser.add_argument("profile_name", help="preset-backed testing profile 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 _build_list_payload(preset_path: str) -> dict[str, object]:
    preset = load_preset(preset_path)
    return {
        "preset": str(preset_path),
        "profiles": preset_profile_names(preset),
    }


def _handle_list(args: argparse.Namespace) -> int:
    if getattr(args, "passthrough_args", []):
        raise ValueError("profiles list does not accept passthrough arguments")
    payload = _build_list_payload(args.preset)
    if args.json:
        print(json.dumps(payload, ensure_ascii=False))
        return 0

    for profile_name in payload["profiles"]:
        print(profile_name)
    return 0


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_profile_execution(args.preset, args.profile_name, passthrough_args)

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

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

    return host.run_profile(args.preset, args.profile_name, passthrough_args)
