"""
Pure auth logic for Lattice.

Core layer - no I/O, use @pre/@post contracts.

This module provides pure functions for provider name validation.
Path computation is in Shell layer (uses pathlib).
"""

from __future__ import annotations

import deal


# Provider name length constraints
_PROVIDER_NAME_MIN_LENGTH = 1
_PROVIDER_NAME_MAX_LENGTH = 50


@deal.pre(lambda char: len(char) == 1)
@deal.post(lambda result: isinstance(result, bool))
def _is_valid_provider_char(char: str) -> bool:
    """Check if a character is valid for provider name.

    Valid characters: letters, digits, hyphens, underscores.

    >>> _is_valid_provider_char("a")
    True
    >>> _is_valid_provider_char("Z")
    True
    >>> _is_valid_provider_char("5")
    True
    >>> _is_valid_provider_char("-")
    True
    >>> _is_valid_provider_char("_")
    True
    >>> _is_valid_provider_char(" ")
    False
    >>> _is_valid_provider_char(".")
    False
    >>> _is_valid_provider_char("!")
    False
    """
    return char.isalnum() or char == "-" or char == "_"


@deal.post(lambda result: result is True or isinstance(result, str))
def validate_provider_name(name: str) -> bool | str:
    """Validate provider name for auth operations.

    Rules:
    - 1-50 characters
    - Alphanumeric, hyphens, underscores only

    Returns:
        True if valid, error message string if invalid

    >>> validate_provider_name("openai")
    True
    >>> validate_provider_name("anthropic-claude")
    True
    >>> validate_provider_name("google_gemini")
    True
    >>> validate_provider_name("a" * 50)  # Edge: max length
    True
    >>> validate_provider_name("a")  # Edge: min length
    True
    >>> validate_provider_name("")
    'Provider name cannot be empty'
    >>> validate_provider_name("a" * 51)
    'Provider name too long (max 50 characters)'
    >>> validate_provider_name("invalid name!")
    'Provider name can only contain letters, numbers, hyphens, and underscores'
    >>> validate_provider_name("test.provider")
    'Provider name can only contain letters, numbers, hyphens, and underscores'
    """
    if len(name) < _PROVIDER_NAME_MIN_LENGTH:
        return "Provider name cannot be empty"
    if len(name) > _PROVIDER_NAME_MAX_LENGTH:
        return "Provider name too long (max 50 characters)"
    for char in name:
        if not _is_valid_provider_char(char):
            return "Provider name can only contain letters, numbers, hyphens, and underscores"
    return True
