"""
VYNDR Edge Calculator
Real edge with vig adjustment + quarter-Kelly criterion.
"""


def calculate_real_edge(model_probability, american_odds):
    """
    Calculate edge AFTER accounting for the vig.
    This is the bettor's actual expected value — not the raw probability gap.

    Args:
        model_probability: Model's estimated probability of the bet hitting (0.0-1.0).
        american_odds: American odds format (e.g., -110, +150).

    Returns:
        Dict with model_probability, implied_probability, real_edge,
        ev_per_dollar, is_positive_ev, min_probability_to_bet.
    """
    if american_odds < 0:
        implied_prob = abs(american_odds) / (abs(american_odds) + 100)
        payout_multiplier = 100 / abs(american_odds)
    else:
        implied_prob = 100 / (american_odds + 100)
        payout_multiplier = american_odds / 100

    real_edge = model_probability - implied_prob
    ev_per_dollar = (model_probability * payout_multiplier) - ((1 - model_probability) * 1.0)

    return {
        'model_probability': round(model_probability, 3),
        'implied_probability': round(implied_prob, 3),
        'real_edge': round(real_edge, 3),
        'ev_per_dollar': round(ev_per_dollar, 3),
        'is_positive_ev': ev_per_dollar > 0,
        'min_probability_to_bet': round(implied_prob, 3)
    }


def kelly_criterion(model_probability, american_odds, fraction=0.25):
    """
    Kelly-optimal bet size. Uses fractional Kelly (quarter) to reduce variance.
    Full Kelly is too aggressive for most bettors.

    Args:
        model_probability: Model's estimated probability of winning (0.0-1.0).
        american_odds: American odds format.
        fraction: Kelly fraction to use (default 0.25 = quarter Kelly).

    Returns:
        Dict with full_kelly_pct, recommended_pct, fraction_used, recommendation.
    """
    if american_odds < 0:
        decimal_odds = 1 + (100 / abs(american_odds))
    else:
        decimal_odds = 1 + (american_odds / 100)

    b = decimal_odds - 1
    p = model_probability
    q = 1 - p

    if b <= 0:
        return {'recommended_pct': 0, 'recommendation': 'NO BET — invalid odds'}

    kelly_pct = ((b * p) - q) / b
    if kelly_pct <= 0:
        return {'recommended_pct': 0, 'recommendation': 'NO BET — negative expected value'}

    recommended = round(kelly_pct * fraction * 100, 1)
    return {
        'full_kelly_pct': round(kelly_pct * 100, 1),
        'recommended_pct': recommended,
        'fraction_used': fraction,
        'recommendation': f'{recommended}% of bankroll'
    }
