"""Solution for selfhost_practice.py."""
import math

PRICES = {
    "gpt-5.4-nano": {"input": 0.20, "cached_input": 0.02, "output": 1.25},
    "gpt-5.4-mini": {"input": 0.75, "cached_input": 0.075, "output": 4.50},
}


def percentile(values, pct):
    ordered = sorted(values)
    if not ordered:
        return 0.0
    rank = max(1, round(pct / 100 * len(ordered)))
    return ordered[min(rank, len(ordered)) - 1]


def paired_p(a, b):
    a_only = sum(x and not y for x, y in zip(a, b))
    b_only = sum(y and not x for x, y in zip(a, b))
    n = a_only + b_only
    if n == 0:
        return 1.0
    k = min(a_only, b_only)
    tail = sum(math.comb(n, i) for i in range(k + 1)) / 2 ** n
    return min(1.0, 2 * tail)


def api_per_1000(model, in_tokens, out_tokens, cached=0):
    p = PRICES[model]
    per_call = ((in_tokens - cached) * p["input"] + cached * p["cached_input"] + out_tokens * p["output"]) / 1e6
    return per_call * 1000


def self_host_per_1000(hourly, per_hour, busy=1.0):
    return hourly / (per_hour * busy) * 1000


def always_on_per_1000(hourly, per_day):
    return hourly * 24 / per_day * 1000
