from __future__ import annotations

from arapy.core.config import ProfileState, describe_profile_state, set_active_profile


def _format_profile_list(state: ProfileState) -> str:
    if not state.available_profiles:
        return (
            "No server profiles found.\n"
            f"Expected profile definitions in {state.profiles_path} and "
            f"{state.credentials_path}."
        )

    lines = ["Configured server profiles:"]
    for profile in state.available_profiles:
        marker = "*" if profile == state.active_profile else " "
        server = state.profile_servers.get(profile)
        if server:
            lines.append(f"{marker} {profile} ({server})")
        else:
            lines.append(f"{marker} {profile}")
    return "\n".join(lines)


def _format_profile_show(state: ProfileState) -> str:
    lines = [
        f"Active profile: {state.active_profile or '<unset>'}",
        f"Server: {state.server or '<unset>'}",
        f"Client ID: {'configured' if state.has_client_id else 'missing'}",
        f"Client secret: {'configured' if state.has_client_secret else 'missing'}",
        f"Profiles file: {state.profiles_path}",
        f"Credentials file: {state.credentials_path}",
    ]
    return "\n".join(lines)


def handle_server_command(args: dict) -> bool:
    service = args.get("service")
    action = args.get("action")

    if service == "list" and not action:
        print(_format_profile_list(describe_profile_state()))
        return True

    if service == "show" and not action:
        print(_format_profile_show(describe_profile_state()))
        return True

    if service == "use" and action:
        try:
            set_active_profile(str(action))
        except ValueError as exc:
            print(str(exc))
            return True
        state = describe_profile_state()
        print(f"Active profile set to {state.active_profile}.")
        if state.server:
            print(f"Server: {state.server}")
        return True

    return False
