from __future__ import annotations

import argparse
import json

from unuforge.runtime.action_dispatch import resolve_preset_action
from unuforge.runtime.presets import load_preset, manifest_path_from_preset, repo_root_from_preset


def register(subparsers: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
    preset_parser = subparsers.add_parser("preset")
    preset_subparsers = preset_parser.add_subparsers(dest="preset_command", required=True)

    inspect_parser = preset_subparsers.add_parser("inspect")
    inspect_parser.add_argument("--preset", required=True, help="release preset JSON path")
    inspect_parser.add_argument("--json", action="store_true", help="emit structured output")
    inspect_parser.set_defaults(handler=_handle_inspect)


def _build_inspect_payload(preset_path: str) -> dict[str, object]:
    preset = load_preset(preset_path)
    repo_root = repo_root_from_preset(preset)
    manifest_path = manifest_path_from_preset(preset)
    testing_profiles = sorted(
        surface["name"]
        for surface in preset["surfaces"]
        if surface["type"] == "profile"
    )
    deployment_actions = {
        name: {"impl": resolve_preset_action(preset, name)["impl"]}
        for name in sorted(
            surface["name"]
            for surface in preset["surfaces"]
            if surface["type"] == "action"
        )
    }
    return {
        "preset": str(preset_path),
        "repo_root": str(repo_root),
        "schema_version": preset["schema_version"],
        "project": {
            "name": preset["project"]["name"],
            "manifest": str(manifest_path),
        },
        "surfaces": preset["surfaces"],
        "runtime": {
            "manifest": str(manifest_path),
            "testing": {
                "profiles": testing_profiles,
            },
            "deployment": {
                "actions": deployment_actions,
            },
        },
    }


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

    print(f"preset: {payload['preset']}")
    print(f"repo_root: {payload['repo_root']}")
    print(f"schema_version: {payload['schema_version']}")
    print(f"project: {payload['project']['name']}")
    print(f"manifest: {payload['project']['manifest']}")
    print("profiles:")
    for profile_name in payload["runtime"]["testing"]["profiles"]:
        print(f"- {profile_name}")
    print("actions:")
    for action_name, action in payload["runtime"]["deployment"]["actions"].items():
        print(f"- {action_name}: {action['impl']}")
    return 0
