"""승인된 상태에서 실행 인자와 확인 화면을 조립한다."""
from __future__ import annotations

from typing import Any

from .confirmation import confirmation_block
from .render import _stage_intent, render_args
from .state import WizardError, WizardState


def _render_argv(rendered: dict[str, Any], *, host_runtime: str) -> list[str]:
    """Flatten render arguments into the canonical render-bundle argv."""
    argv = ["--lead-runtime", host_runtime]
    for name, raw_value in rendered.items():
        values = raw_value if isinstance(raw_value, list) else [raw_value]
        for value in values:
            if not isinstance(value, str):
                raise WizardError(
                    f"wizard render arg --{name} must be a string"
                )
            argv.extend([f"--{name}", value])
    return argv


def _wizard_persist_actions(state: WizardState) -> list[dict[str, str]]:
    if state.task_type != "release-handoff":
        return []
    if not state.pr_template_path:
        return []
    if state.pr_template_scope not in ("project", "global"):
        return []
    return [
        {
            "command": "config.set",
            "key": "pr-template-path",
            "scope": state.pr_template_scope,
            "value": state.pr_template_path,
        }
    ]


def wizard_outcome(state: WizardState) -> dict[str, Any]:
    """Public outcome for callers that need launch data and follow-up writes.

    `renderArgs` carries only what `okstra render-bundle` accepts, so a caller
    can pass every entry through unfiltered — which is exactly what the
    okstra-run skill is told to do. Signals the skill consumes itself, like the
    unattended stage chain, live under `orchestration`; mixing them into
    `renderArgs` made the renderer reject the wizard's own output.
    """
    if state.aborted:
        raise WizardError("wizard was aborted by the user — outcome is unavailable")
    if state.confirmed is not True:
        raise WizardError("wizard is not complete — outcome is unavailable")
    rendered = render_args(state)
    return {
        "renderArgs": rendered,
        "renderArgv": _render_argv(rendered, host_runtime=state.host_runtime),
        "orchestration": {"chainStages": _stage_intent(state).chain_stages},
        "persistActions": _wizard_persist_actions(state),
        "confirmationText": state.user_authorization.get("prompt") or confirmation_block(state),
        "userAuthorization": state.user_authorization or None,
    }
