"""Computer assignment: implement a binomial options pricer.

Download this single file, fill in ``price`` below, and run the included tests:

    uv run --no-project --with pytest python -m pytest test_binomial_pricer_assignment.py

All times are measured in years. ``rate`` and ``vol`` are annualized. Cash
dividends are fixed dollar amounts paid at the given ex-dividend times.
The tests are deliberately broad: start with the one-step cases, then add
multiple steps, interest, dividends, and American early exercise.
"""

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from math import exp, log, sqrt

import pytest


class OptionType(Enum):
    CALL = "call"
    PUT = "put"


class ExerciseType(Enum):
    EUROPEAN = "european"
    AMERICAN = "american"


@dataclass(frozen=True, slots=True)
class Dividend:
    t_div: float
    amount: float


def price(
    side: OptionType,
    strike: float,
    t_exp: float,
    exercise: ExerciseType,
    stock_px: float,
    rate: float,
    vol: float,
    dividends: list[Dividend],
    n_steps: int,
) -> float:
    """Return the option value from a Cox-Ross-Rubinstein binomial tree.

    Implement this function. Do not change its signature or the types above.

    Suggested sequence:
    1. At each time step, compute the up/down stock multipliers, the
       risk-neutral up probability, and the one-step discount factor.
    2. Fill ONE list with option payoffs at expiry. Work backward, replacing
       each entry with the discounted value of its two child nodes. Do not
       construct a two-dimensional tree.
    3. For American options, compare continuation with exercise at every node.
       A cash dividend can make exercise just before or just after its
       ex-dividend time optimal.
    4. To keep cash-dividend trees recombining, one approach is to build the
       lattice on stock price minus the present value of future dividends.
       Add the value of remaining dividends back when checking exercise.
    5. Handle zero time and zero volatility, and reject invalid inputs as the
       tests specify. Dividend times must fall exactly on lattice steps.

    You may add private helper functions above or below this function.
    The production implementation is not needed to complete the assignment.
    """
    pass


def _price(
    side: OptionType = OptionType.CALL,
    strike: float = 100.0,
    t_exp: float = 1.0,
    exercise: ExerciseType = ExerciseType.EUROPEAN,
    stock_px: float = 100.0,
    rate: float = 0.0,
    vol: float = log(1.25),
    dividends: list[Dividend] | None = None,
    n_steps: int = 1,
) -> float:
    """Supply common defaults so each test highlights one change."""
    return price(
        side,
        strike,
        t_exp,
        exercise,
        stock_px,
        rate,
        vol,
        [] if dividends is None else dividends,
        n_steps,
    )


def test_one_step_call_by_hand() -> None:
    # S goes from 100 to 125 or 80. At r=0, q=(100-80)/(125-80)=4/9.
    # The call pays 25 or 0, so its value is (4/9)*25 = 100/9.
    assert _price() == pytest.approx(100 / 9)


def test_one_step_put_by_hand() -> None:
    # The matching put pays 0 or 20, so its value is (5/9)*20 = 100/9.
    assert _price(side=OptionType.PUT) == pytest.approx(100 / 9)


def test_two_step_call_by_hand() -> None:
    # Choose annual vol so each half-year step still has u=1.25, d=0.8.
    # Terminal stock prices: 156.25, 100, 64. Strike 90 gives 66.25, 10, 0.
    two_step_vol = log(1.25) * sqrt(2)
    expected = (4 / 9) ** 2 * 66.25 + 2 * (4 / 9) * (5 / 9) * 10
    assert _price(strike=90, vol=two_step_vol, n_steps=2) == pytest.approx(expected)


def test_two_step_put_by_hand() -> None:
    # At strike 90, only the down/down path pays: 90-64=26.
    two_step_vol = log(1.25) * sqrt(2)
    expected = (5 / 9) ** 2 * 26
    assert _price(
        side=OptionType.PUT, strike=90, vol=two_step_vol, n_steps=2
    ) == pytest.approx(expected)


@pytest.mark.parametrize("n_steps", [1, 2, 5, 50, 200])
def test_european_parity_without_rates_or_dividends(n_steps: int) -> None:
    call = _price(strike=90, vol=0.2, n_steps=n_steps)
    put = _price(side=OptionType.PUT, strike=90, vol=0.2, n_steps=n_steps)
    assert call - put == pytest.approx(100 - 90)


def test_many_step_european_call_approaches_black_scholes_at_zero_rates() -> None:
    # The continuous-model benchmark for S=K=100, T=1, sigma=20%, r=0.
    benchmark = 7.965567455
    coarse = _price(vol=0.2, n_steps=100)
    fine = _price(vol=0.2, n_steps=400)
    assert abs(fine - benchmark) < abs(coarse - benchmark)
    assert fine == pytest.approx(benchmark, abs=0.02)


def test_one_step_call_with_interest_by_hand() -> None:
    growth = exp(0.05)
    q = (growth - 0.8) / (1.25 - 0.8)
    expected = exp(-0.05) * q * 25
    assert _price(rate=0.05) == pytest.approx(expected)


def test_one_step_put_with_interest_by_hand() -> None:
    growth = exp(0.05)
    q = (growth - 0.8) / (1.25 - 0.8)
    expected = exp(-0.05) * (1 - q) * 20
    assert _price(side=OptionType.PUT, rate=0.05) == pytest.approx(expected)


def test_interest_put_call_parity() -> None:
    call = _price(rate=0.05, n_steps=100, vol=0.2)
    put = _price(side=OptionType.PUT, rate=0.05, n_steps=100, vol=0.2)
    assert call - put == pytest.approx(100 - 100 * exp(-0.05))


def test_two_step_cash_dividend_call_by_hand() -> None:
    # A $5 dividend at t=0.5 leaves a $95 dividend-free component at r=0.
    # At expiry it can be 136.8, 95, or 95/1.2**2. Only up/up pays.
    q = 5 / 11
    expected = q**2 * (95 * 1.2**2 - 100)
    assert _price(
        vol=log(1.2) * sqrt(2),
        dividends=[Dividend(0.5, 5)],
        n_steps=2,
    ) == pytest.approx(expected)


def test_two_step_cash_dividend_put_by_hand() -> None:
    q = 5 / 11
    down = 1 - q
    expected = 2 * q * down * 5 + down**2 * (100 - 95 / 1.2**2)
    assert _price(
        side=OptionType.PUT,
        vol=log(1.2) * sqrt(2),
        dividends=[Dividend(0.5, 5)],
        n_steps=2,
    ) == pytest.approx(expected)


def test_rates_and_two_dividends_satisfy_adjusted_parity() -> None:
    dividends = [Dividend(0.75, 2), Dividend(0.25, 1.5)]  # unsorted is fine
    call = _price(strike=90, rate=0.04, vol=0.25, dividends=dividends, n_steps=100)
    put = _price(
        side=OptionType.PUT,
        strike=90,
        rate=0.04,
        vol=0.25,
        dividends=dividends,
        n_steps=100,
    )
    pv_dividends = sum(d.amount * exp(-0.04 * d.t_div) for d in dividends)
    assert call - put == pytest.approx(100 - pv_dividends - 90 * exp(-0.04))


def test_cash_dividends_lower_european_calls_and_raise_puts() -> None:
    dividends = [Dividend(0.5, 3)]
    assert _price(rate=0.04, vol=0.2, dividends=dividends, n_steps=100) < _price(
        rate=0.04, vol=0.2, n_steps=100
    )
    assert _price(
        side=OptionType.PUT, rate=0.04, vol=0.2, dividends=dividends, n_steps=100
    ) > _price(side=OptionType.PUT, rate=0.04, vol=0.2, n_steps=100)


def test_duplicate_dividend_dates_add_together() -> None:
    split = _price(vol=0.2, n_steps=20, dividends=[Dividend(0.5, 1), Dividend(0.5, 2)])
    combined = _price(vol=0.2, n_steps=20, dividends=[Dividend(0.5, 3)])
    assert split == pytest.approx(combined)


def test_american_call_without_dividends_equals_european_call() -> None:
    assert _price(
        exercise=ExerciseType.AMERICAN, rate=0.05, vol=0.2, n_steps=200
    ) == pytest.approx(_price(rate=0.05, vol=0.2, n_steps=200))


def test_american_put_exercises_at_an_interior_node() -> None:
    # Two half-year steps: S=100 -> 80 -> 64 on the down/down path.
    # At the first down node the put's $20 exercise value beats continuation.
    rate = 0.1
    discount = exp(-rate / 2)
    q = (exp(rate / 2) - 0.8) / (1.25 - 0.8)
    expected = discount * (1 - q) * 20
    american = _price(
        side=OptionType.PUT,
        rate=rate,
        vol=log(1.25) * sqrt(2),
        n_steps=2,
        exercise=ExerciseType.AMERICAN,
    )
    european = _price(
        side=OptionType.PUT, rate=rate, vol=log(1.25) * sqrt(2), n_steps=2
    )
    assert american == pytest.approx(expected)
    assert american > european


def test_deep_in_the_money_american_put_can_exercise_immediately() -> None:
    assert _price(
        side=OptionType.PUT, strike=130, rate=0.05, exercise=ExerciseType.AMERICAN
    ) == pytest.approx(30)
    assert _price(side=OptionType.PUT, strike=130, rate=0.05) < 30


def test_american_call_exercises_just_before_a_cash_dividend() -> None:
    # A large cash dividend makes pre-dividend exercise optimal at the up node.
    rate = 0.05
    dividend = 12.0
    component = 100 - dividend * exp(-rate / 2)
    q = (exp(rate / 2) - 0.8) / (1.25 - 0.8)
    discount = exp(-rate / 2)
    up_post_dividend = component * 1.25
    down_post_dividend = component * 0.8
    up_continuation = discount * (
        q * (component * 1.25**2 - 80) + (1 - q) * (component - 80)
    )
    up_exercise_before_dividend = up_post_dividend + dividend - 80
    down_continuation = discount * q * (component - 80)
    assert up_exercise_before_dividend > up_continuation
    assert down_continuation > max(down_post_dividend + dividend - 80, 0)
    expected = discount * (
        q * up_exercise_before_dividend + (1 - q) * down_continuation
    )
    american = _price(
        strike=80,
        rate=rate,
        vol=log(1.25) * sqrt(2),
        dividends=[Dividend(0.5, dividend)],
        n_steps=2,
        exercise=ExerciseType.AMERICAN,
    )
    european = _price(
        strike=80,
        rate=rate,
        vol=log(1.25) * sqrt(2),
        dividends=[Dividend(0.5, dividend)],
        n_steps=2,
    )
    assert american == pytest.approx(expected)
    assert american > european


def test_american_put_can_exercise_just_after_a_cash_dividend() -> None:
    rate = 0.1
    dividend = 10.0
    component = 100 - dividend * exp(-rate / 2)
    q = (exp(rate / 2) - 0.8) / (1.25 - 0.8)
    discount = exp(-rate / 2)
    down_post_dividend = component * 0.8
    down_exercise_after_dividend = 100 - down_post_dividend
    down_exercise_before_dividend = 100 - (down_post_dividend + dividend)
    down_continuation = discount * (
        q * (100 - component) + (1 - q) * (100 - component * 0.8**2)
    )
    assert down_exercise_after_dividend > down_exercise_before_dividend
    assert down_exercise_after_dividend > down_continuation

    up_continuation = discount * (1 - q) * (100 - component)
    expected = discount * (q * up_continuation + (1 - q) * down_exercise_after_dividend)
    assert _price(
        side=OptionType.PUT,
        rate=rate,
        vol=log(1.25) * sqrt(2),
        dividends=[Dividend(0.5, dividend)],
        n_steps=2,
        exercise=ExerciseType.AMERICAN,
    ) == pytest.approx(expected)


def test_american_option_is_never_cheaper_than_european() -> None:
    dividends = [Dividend(0.25, 2), Dividend(0.75, 3)]
    for side in OptionType:
        american = _price(
            side=side,
            rate=0.04,
            vol=0.3,
            dividends=dividends,
            n_steps=100,
            exercise=ExerciseType.AMERICAN,
        )
        european = _price(
            side=side, rate=0.04, vol=0.3, dividends=dividends, n_steps=100
        )
        assert american >= european


def test_zero_volatility_is_a_deterministic_limit() -> None:
    rate = 0.05
    expected = exp(-rate) * max(100 * exp(rate) - 100, 0)
    assert _price(rate=rate, vol=0, n_steps=10) == pytest.approx(expected)


def test_expiry_today_returns_intrinsic_value() -> None:
    assert _price(t_exp=0, strike=90, vol=0) == pytest.approx(10)
    assert _price(side=OptionType.PUT, t_exp=0, strike=90, vol=0) == 0


@pytest.mark.parametrize(
    ("change", "message"),
    [
        ({"n_steps": 0}, "n_steps"),
        ({"n_steps": True}, "n_steps"),
        ({"strike": -1}, "strike"),
        ({"stock_px": 0}, "stock_px"),
        ({"t_exp": -1}, "t_exp"),
        ({"vol": -0.1}, "vol"),
        ({"rate": float("nan")}, "rate"),
        ({"vol": float("inf")}, "vol"),
        ({"dividends": [Dividend(0.3, 1)], "n_steps": 4}, "lattice step"),
        ({"dividends": [Dividend(1e-13, 1)], "n_steps": 4}, "lattice step"),
        ({"dividends": [Dividend(1 - 1e-13, 1)], "n_steps": 4}, "lattice step"),
        ({"dividends": [Dividend(0, 1)]}, "strictly between"),
        ({"dividends": [Dividend(1, 1)]}, "strictly between"),
        ({"dividends": [Dividend(0.5, -1)], "n_steps": 2}, "nonnegative"),
        ({"dividends": [Dividend(0.5, 200)], "n_steps": 2}, "exceed"),
        ({"rate": 0.5, "vol": 0.01}, "probability"),
    ],
)
def test_invalid_inputs_are_rejected(change: dict[str, object], message: str) -> None:
    with pytest.raises(ValueError, match=message):
        _price(**change)  # type: ignore[arg-type]


def test_wrong_enum_types_are_rejected() -> None:
    with pytest.raises(TypeError, match="OptionType"):
        _price(side="call")  # type: ignore[arg-type]
    with pytest.raises(TypeError, match="ExerciseType"):
        _price(exercise="american")  # type: ignore[arg-type]


def test_wrong_dividend_type_is_rejected() -> None:
    with pytest.raises(TypeError, match="Dividend"):
        _price(dividends=[(0.5, 2)], n_steps=2)  # type: ignore[list-item]
