from decimal import Decimal, InvalidOperation

from .constants import ContractTerminationReason
from .exceptions import (
    InvalidContractDatesError,
    InvalidContractOfferError,
    InvalidTerminationReasonError,
)


MONEY_MAX_DIGITS = 18
MONEY_DECIMAL_PLACES = 2


def validate_offer_dates(*, expires_at, now):
    if expires_at is None or expires_at <= now:
        raise InvalidContractOfferError(
            "Offer expiration must be in the future."
        )


def validate_contract_dates(*, start_date, end_date):
    if start_date is None or end_date is None:
        raise InvalidContractDatesError(
            "Contract start and end dates are required."
        )
    if end_date <= start_date:
        raise InvalidContractDatesError(
            "Contract end date must be after start date."
        )


def validate_positive_duration(value):
    if isinstance(value, bool) or not isinstance(value, int) or value < 1:
        raise InvalidContractOfferError(
            "Contract duration must be at least one month."
        )
    return value


def validate_money(value, name):
    if value is None or isinstance(value, bool):
        raise InvalidContractOfferError(f"{name} must be a valid amount.")

    try:
        amount = value if isinstance(value, Decimal) else Decimal(str(value))
    except (InvalidOperation, TypeError, ValueError) as exc:
        raise InvalidContractOfferError(
            f"{name} must be a valid amount."
        ) from exc

    if not amount.is_finite() or amount < 0:
        raise InvalidContractOfferError(
            f"{name} cannot be negative or non-finite."
        )

    normalized = amount.normalize()
    exponent = normalized.as_tuple().exponent
    decimal_places = max(-exponent, 0)
    integer_digits = max(len(normalized.as_tuple().digits) + exponent, 0)

    if decimal_places > MONEY_DECIMAL_PLACES:
        raise InvalidContractOfferError(
            f"{name} cannot have more than {MONEY_DECIMAL_PLACES} decimal places."
        )

    if integer_digits + decimal_places > MONEY_MAX_DIGITS:
        raise InvalidContractOfferError(
            f"{name} exceeds the supported precision."
        )

    return amount


def validate_termination_reason(reason):
    valid_reasons = set(ContractTerminationReason.values)
    if reason not in valid_reasons:
        raise InvalidTerminationReasonError(
            "A valid contract termination reason is required."
        )
    return reason
