from __future__ import annotations

import typer

from flow_xhs.cli.commands.search import run_user_search
from flow_xhs.cli.spec.runtime_contracts import (
    command_description,
    command_option,
    emit_command_help_if_empty,
    emit_group_help_if_empty,
    group_summary,
)
from flow_xhs.contracts.command_inputs import UserGetInput
from flow_xhs.services.user_get import execute_user_get
from flow_xhs.services.user_self import execute_user_self
from flow_xhs.cli.context import CliContext
from flow_xhs.cli.runtime import run_async_command
from flow_xhs.cli.utils import load_json_input, pick_cli_or_input, resolve_account_uid

app = typer.Typer(
    help=group_summary(("user",)),
    no_args_is_help=False,
    options_metavar="[OPTIONS]",
    subcommand_metavar="<COMMAND>",
)


def run_user_get_command(
    *,
    ctx: typer.Context,
    user_url: str | None,
    input_file: str | None,
) -> None:
    emit_command_help_if_empty(ctx, ("user", "get"))

    cli_ctx: CliContext = ctx.obj
    payload = load_json_input(input_file)
    resolved_account_uid: str | None = None

    async def _run():
        nonlocal resolved_account_uid
        resolved_account_uid = resolve_account_uid()
        validated = UserGetInput(
            user_url=pick_cli_or_input(
                ctx=ctx,
                param_name="user_url",
                cli_value=user_url,
                payload=payload,
                payload_key="user_url",
            ),
            account_uid=resolved_account_uid,
        )
        return await execute_user_get(
            user_id=validated.user_id,
            xsec_token=validated.xsec_token,
            xsec_source=validated.xsec_source,
            account_uid=validated.account_uid,
        )

    run_async_command(
        ctx=cli_ctx,
        command="user.get",
        func=_run,
        account_uid=lambda: resolved_account_uid,
    )


@app.callback(invoke_without_command=True)
def user_group(ctx: typer.Context):
    if ctx.invoked_subcommand:
        return
    emit_group_help_if_empty(ctx, ("user",))


@app.command("get")
def user_get(
    ctx: typer.Context,
    user_url: str | None = command_option(("user", "get"), "user_url", None),
    input_file: str | None = command_option(("user", "get"), "input", None),
):
    """Canonical 路径：`flow-xhs user get`。"""
    run_user_get_command(
        ctx=ctx,
        user_url=user_url,
        input_file=input_file,
    )


user_get.__doc__ = command_description(("user", "get"))


@app.command("search")
def user_search(
    ctx: typer.Context,
    keyword: str | None = command_option(("user", "search"), "keyword", None),
    size: int | None = command_option(("user", "search"), "size"),
    input_file: str | None = command_option(("user", "search"), "input", None),
):
    run_user_search(
        ctx=ctx,
        keyword=keyword,
        size=size,
        input_file=input_file,
    )


user_search.__doc__ = command_description(("user", "search"))


@app.command("self")
def user_self(
    ctx: typer.Context,
):
    """查询当前登录账号自己的用户信息。"""
    cli_ctx: CliContext = ctx.obj
    resolved_account_uid: str | None = None

    async def _run():
        nonlocal resolved_account_uid
        resolved_account_uid = resolve_account_uid()
        return await execute_user_self(account_uid=resolved_account_uid)

    run_async_command(
        ctx=cli_ctx,
        command="user.self",
        func=_run,
        account_uid=lambda: resolved_account_uid,
    )
