"""Run after installing the supplied original source: python -m pip install ./source.
All inputs below are invented practice assumptions, not market observations.
Prices are currency units per share. Rates/volatility are annual decimals.
"""
import math
import bs


def validate_inputs(share_price, strike_price, annual_rate, years_remaining, annual_volatility):
    values = (share_price, strike_price, annual_rate, years_remaining, annual_volatility)
    if not all(math.isfinite(value) for value in values):
        raise ValueError("All inputs must be finite numbers.")
    if min(share_price, strike_price, years_remaining, annual_volatility) <= 0:
        raise ValueError("Prices, years remaining and volatility must be positive.")


def reference_prices(s, k, r, t, sigma):
    """Independent normal calculation using the standard library's erf function."""
    d1 = (math.log(s / k) + (r + sigma**2 / 2) * t) / (sigma * math.sqrt(t))
    d2 = d1 - sigma * math.sqrt(t)
    normal = lambda x: 0.5 * (1 + math.erf(x / math.sqrt(2)))
    return (s * normal(d1) - k * math.exp(-r * t) * normal(d2),
            k * math.exp(-r * t) * normal(-d2) - s * normal(-d1))


def main():
    share_price = 147.30
    strike_price = 150.0
    annual_rate = 0.001         # 0.1%, not 10%
    calendar_days = 60
    annual_volatility = 0.45    # 45%, not 4,500%
    years_remaining = calendar_days / 365
    inputs = (share_price, strike_price, annual_rate, years_remaining, annual_volatility)
    validate_inputs(*inputs)
    call = bs.bs_call(*inputs)
    put = bs.bs_put(*inputs)
    print(f"Call per share: {call:.6f}")
    print(f"Put per share:  {put:.6f}")
    discounted_strike = strike_price * math.exp(-annual_rate * years_remaining)
    parity_error = call - put - (share_price - discounted_strike)
    print(f"Consistency difference: {parity_error:.10f}")
    reference_call, reference_put = reference_prices(*inputs)
    assert abs(call - 9.518562265392394) < 1e-8, "Original call example changed"
    assert abs(put - 12.1939067576814) < 1e-8, "Original put example changed"
    assert abs(parity_error) < 1e-8, "Put-call parity failed"
    assert abs(call - reference_call) < 0.0001, "Call differs from erf reference"
    assert abs(put - reference_put) < 0.0001, "Put differs from erf reference"
    assert max(0, share_price - discounted_strike) - 1e-8 <= call <= share_price + 1e-8
    assert max(0, discounted_strike - share_price) - 1e-8 <= put <= discounted_strike + 1e-8
    print("PASS: known answers, consistency, price bounds and independent reference")


if __name__ == "__main__":
    main()
