"""Provider credentials setup service.

Shared logic for prompting users to configure AI provider API keys.
Used by both login and signup flows.
"""

from cli.infrastructure.console import Confirm, Prompt, Text, get_console
from alloy_runtime_sdk.api_client.client import ApiClient
from alloy_runtime_types.dtos.organization_credentials import (
    CreateOrganizationCredentialRequest,
)
from alloy_runtime_types.enums.provider import Provider

# Provider definitions: (display_name, Provider enum, env_hint, example_prefix)
PROVIDERS = [
    ("X.Ai", Provider.XAI, "XAI_API_KEY", "..."),
    ("Google", Provider.GOOGLE, "GOOGLE_API_KEY", "..."),
    ("Anthropic", Provider.ANTHROPIC, "ANTHROPIC_API_KEY", "sk-ant-..."),
    ("OpenAI", Provider.OPENAI, "OPENAI_API_KEY", "sk-..."),
    ("OpenRouter", Provider.OPENROUTER, "OPENROUTER_API_KEY", "sk-or-..."),
]


async def prompt_provider_credentials(api_url: str, api_key: str) -> int:
    """Prompt user to configure provider API keys.

    Args:
        api_url: API server base URL
        api_key: User's API key for authenticated requests

    Returns:
        Number of providers successfully configured
    """
    console = get_console()

    console.print("\nAI Provider Credentials Setup", markup=False, highlight=False)
    console.print(
        "Configure API keys for AI providers to start using the platform.\n",
        markup=False,
        highlight=False,
    )

    configured_count = 0

    async with ApiClient(base_url=api_url, api_key=api_key) as client:
        for display_name, provider_enum, _env_hint, example_prefix in PROVIDERS:
            if Confirm.ask(Text(f"Configure {display_name} API key?"), default=False):
                api_key_value = Prompt.ask(
                    Text(f"{display_name} API Key (e.g., {example_prefix})"),
                    password=True,
                )

                if api_key_value and api_key_value.strip():
                    try:
                        request = CreateOrganizationCredentialRequest(
                            credential_type_id="org_provider",
                            name=f"{display_name} API Key",
                            secret=api_key_value.strip(),
                            provider_key=provider_enum,
                            description=f"{display_name} API key configured during signup",
                        )
                        await client.create_organization_credential(request)
                        console.print(
                            f"✓ {display_name} credential saved!",
                            markup=False,
                            highlight=False,
                        )
                        configured_count += 1
                    except Exception as e:
                        console.print(
                            f"✗ Failed to save {display_name} credential: {e}",
                            markup=False,
                            highlight=False,
                        )

    if configured_count > 0:
        console.print(
            f"\nConfigured {configured_count} provider(s)!",
            markup=False,
            highlight=False,
        )
        console.print(
            "You're ready to use Alloy Runtime!", markup=False, highlight=False
        )
    else:
        console.print("\nNo providers configured.", markup=False, highlight=False)
        console.print(
            "You can add them later with the credentials commands.",
            markup=False,
            highlight=False,
        )

    return configured_count
