"""Admin credentials create command implementation."""

from decimal import Decimal
from typing import Optional

import typer

from cli.commands.admin.credentials.create.presenter import (
    present_credential_create_success,
)
from cli.commands.flag_utils import validate_provider
from cli.commands.shared_flags import (
    CREDENTIAL_VALUE,
    DESCRIPTION,
    NAME,
    PROVIDER_REQUIRED,
)
from cli.infrastructure.command import async_command, authenticated_client
from alloy_runtime_types.dtos.credentials import CreateSystemCredentialRequest


def admin_credentials_create_command(
    credential_type_id: str = typer.Option(
        ...,
        "--type",
        help="Credential type (e.g., system_provider)",
    ),
    name: str = NAME,
    plaintext_value: str = CREDENTIAL_VALUE,
    provider: str = PROVIDER_REQUIRED,
    description: Optional[str] = DESCRIPTION,
    priority: int = typer.Option(
        0,
        "--priority",
        help="Selection priority (default: 0)",
    ),
    is_default: bool = typer.Option(
        False,
        "--default",
        help="Default credential for provider",
    ),
    daily_request_limit: Optional[int] = typer.Option(
        None,
        "--daily-limit",
        help="Daily request limit",
    ),
    monthly_cost_limit_usd: Optional[str] = typer.Option(
        None,
        "--monthly-cost-limit",
        help="Monthly USD limit (e.g., 50.00)",
    ),
    requests_per_minute_limit: Optional[int] = typer.Option(
        None,
        "--rate-limit",
        help="Requests/minute limit",
    ),
) -> None:
    """Create a system credential (requires system admin).

    SECURITY: Use env var: --value "$OPENAI_API_KEY"

    Examples:

        alloy admin credentials create --type system_provider -n "OpenAI" --value "sk-..." -p openai
        alloy admin credentials create --type system_provider -n "Default" --value "sk-..." -p openrouter --default
    """
    _execute_create(
        credential_type_id=credential_type_id,
        name=name,
        plaintext_value=plaintext_value,
        provider=provider,
        description=description,
        priority=priority,
        is_default=is_default,
        daily_request_limit=daily_request_limit,
        monthly_cost_limit_usd=monthly_cost_limit_usd,
        requests_per_minute_limit=requests_per_minute_limit,
    )


@async_command
async def _execute_create(
    credential_type_id: str,
    name: str,
    plaintext_value: str,
    provider: str,
    description: Optional[str],
    priority: int,
    is_default: bool,
    daily_request_limit: Optional[int],
    monthly_cost_limit_usd: Optional[str],
    requests_per_minute_limit: Optional[int],
) -> None:
    """Execute the credential creation operation.

    Args:
        credential_type_id: Credential type ID
        name: Friendly name
        plaintext_value: API key value
        provider: Provider key string
        description: Optional description
        priority: Priority for selection
        is_default: Whether this is the default for the provider
        daily_request_limit: Optional daily request limit
        monthly_cost_limit_usd: Optional monthly cost limit as string
        requests_per_minute_limit: Optional rate limit

    Raises:
        ConfigurationError: If environment variables are missing
        AuthenticationError: If API key is invalid
        ForbiddenError: If user is not system admin
        ValidationError: If request data is invalid
        ConflictError: If duplicate default credential exists
        ServerError: If server returns 5xx error
    """
    # Validate and convert provider string to enum
    provider_enum = validate_provider(provider)

    # Convert monthly cost limit string to Decimal if provided
    monthly_cost_decimal = None
    if monthly_cost_limit_usd is not None:
        try:
            monthly_cost_decimal = Decimal(monthly_cost_limit_usd)
        except Exception:
            raise typer.BadParameter(
                f"Invalid monthly cost limit '{monthly_cost_limit_usd}'. Must be a valid decimal number (e.g., '50.00')"
            )

    # Build request
    request = CreateSystemCredentialRequest(
        credential_type_id=credential_type_id,
        name=name,
        secret=plaintext_value,
        provider_key=provider_enum,
        description=description,
        priority=priority,
        is_default=is_default,
        daily_request_limit=daily_request_limit,
        monthly_cost_limit_usd=monthly_cost_decimal,
        requests_per_minute_limit=requests_per_minute_limit,
    )

    # Execute API call with authenticated client
    async with authenticated_client() as (_config, client):
        response = await client.create_system_credential(request)

    # Present success output
    present_credential_create_success(response)
