"""Compare adding cold milk now and at the end of a fixed wait."""

import argparse
import json
import math

ROOM_C = 22.0
COFFEE_C = 85.0
MILK_C = 5.0
COFFEE_MASS_KG = 0.200
MILK_MASS_KG = 0.030
SPECIFIC_HEAT = 4180.0  # J/(kg K), assigned to both liquids
COFFEE_CAPACITY = COFFEE_MASS_KG * SPECIFIC_HEAT
MILK_CAPACITY = MILK_MASS_KG * SPECIFIC_HEAT
TOTAL_CAPACITY = COFFEE_CAPACITY + MILK_CAPACITY
BLACK_CONDUCTANCE = 0.7  # W/K
FASTER_MIXED_CONDUCTANCE = 1.1
WAIT_SECONDS = 600


def mix(coffee_c, milk_c):
    return (COFFEE_CAPACITY * coffee_c + MILK_CAPACITY * milk_c) / TOTAL_CAPACITY


def cool(start_c, conductance, capacity, seconds):
    return ROOM_C + (start_c - ROOM_C) * math.exp(-conductance * seconds / capacity)


def euler_cool(start_c, conductance, capacity, seconds):
    # Independent numerical check of the analytic curve in 0.1 s steps.
    step = 0.1
    temperature = start_c
    for _ in range(round(seconds / step)):
        temperature -= step * conductance * (temperature - ROOM_C) / capacity
    return temperature


def compare(black_conductance, mixed_conductance, milk_c, seconds):
    mixed_at_start = mix(COFFEE_C, milk_c)
    black_before_milk = cool(COFFEE_C, black_conductance, COFFEE_CAPACITY, seconds)
    early = cool(mixed_at_start, mixed_conductance, TOTAL_CAPACITY, seconds)
    late = mix(black_before_milk, milk_c)
    early_check = euler_cool(mixed_at_start, mixed_conductance, TOTAL_CAPACITY, seconds)
    black_check = euler_cool(COFFEE_C, black_conductance, COFFEE_CAPACITY, seconds)
    error = max(abs(early - early_check), abs(late - mix(black_check, milk_c)))
    if error >= 0.002:
        raise RuntimeError(f"Integration differs from analytic result by {error:.6f} °C")
    return {
        "wait_s": seconds,
        "milk_c": milk_c,
        "black_conductance_w_per_k": black_conductance,
        "mixed_conductance_w_per_k": mixed_conductance,
        "just_mixed_at_start_c": round(mixed_at_start, 6),
        "black_before_late_milk_c": round(black_before_milk, 6),
        "add_early_c": round(early, 6),
        "add_late_c": round(late, 6),
        "early_minus_late_c": round(early - late, 6),
        "max_euler_error_c": round(error, 6),
    }


def draw(path):
    import matplotlib
    matplotlib.use("Agg")
    from matplotlib import pyplot as plt

    minutes = [index / 12 for index in range(121)]
    black = [cool(COFFEE_C, BLACK_CONDUCTANCE, COFFEE_CAPACITY, m * 60) for m in minutes]
    mixed_start = mix(COFFEE_C, MILK_C)
    late = mix(black[-1], MILK_C)
    fig, axes = plt.subplots(1, 2, figsize=(10.4, 4.0), sharey=True, layout="constrained")
    fig.suptitle("Adding milk now or after 10 minutes", fontsize=15, fontweight="bold")
    for ax, conductance, title in zip(
        axes,
        (BLACK_CONDUCTANCE, FASTER_MIXED_CONDUCTANCE),
        ("Same heat loss coefficient", "Faster heat loss after mixing"),
    ):
        early = [cool(mixed_start, conductance, TOTAL_CAPACITY, m * 60) for m in minutes]
        ax.plot(minutes, black, color="#944329", linestyle="--", label="Black coffee")
        ax.plot(minutes, early, color="#175f97", label="Milk at the start", linewidth=2)
        ax.plot([10, 10], [black[-1], late], color="#944329", linewidth=1.5)
        ax.scatter([10, 10], [early[-1], late], color=["#175f97", "#944329"], zorder=4)
        ax.set(title=title, xlim=(0, 10.5), ylim=(45, 88), xlabel="Minutes since pouring")
        ax.set_xticks([0, 2, 4, 6, 8, 10])
        ax.grid(axis="y", alpha=0.3)
        ax.legend(loc="upper right", fontsize=9, frameon=False)
    axes[0].set_ylabel("Temperature (°C)")
    fig.savefig(path, dpi=130, facecolor="white")
    plt.close(fig)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--figure", metavar="PNG", help="render chart with Matplotlib")
    args = parser.parse_args()
    reports = {
        "same_conductance": compare(BLACK_CONDUCTANCE, BLACK_CONDUCTANCE, MILK_C, WAIT_SECONDS),
        "higher_mixed_conductance": compare(
            BLACK_CONDUCTANCE, FASTER_MIXED_CONDUCTANCE, MILK_C, WAIT_SECONDS
        ),
        "room_temperature_milk": compare(
            BLACK_CONDUCTANCE, BLACK_CONDUCTANCE, ROOM_C, WAIT_SECONDS
        ),
        "zero_wait": compare(BLACK_CONDUCTANCE, BLACK_CONDUCTANCE, MILK_C, 0),
        "no_heat_loss": compare(0.0, 0.0, MILK_C, WAIT_SECONDS),
    }
    late = mix(cool(COFFEE_C, BLACK_CONDUCTANCE, COFFEE_CAPACITY, WAIT_SECONDS), MILK_C)
    initial_mixed = mix(COFFEE_C, MILK_C)
    break_even = -TOTAL_CAPACITY / WAIT_SECONDS * math.log(
        (late - ROOM_C) / (initial_mixed - ROOM_C)
    )
    target_c = 54.0
    black_target_c = (TOTAL_CAPACITY * target_c - MILK_CAPACITY * MILK_C) / COFFEE_CAPACITY
    early_target_seconds = TOTAL_CAPACITY / BLACK_CONDUCTANCE * math.log(
        (initial_mixed - ROOM_C) / (target_c - ROOM_C)
    )
    late_target_seconds = COFFEE_CAPACITY / BLACK_CONDUCTANCE * math.log(
        (COFFEE_C - ROOM_C) / (black_target_c - ROOM_C)
    )
    early_at_target = cool(
        initial_mixed, BLACK_CONDUCTANCE, TOTAL_CAPACITY, early_target_seconds
    )
    late_at_target = mix(
        cool(COFFEE_C, BLACK_CONDUCTANCE, COFFEE_CAPACITY, late_target_seconds), MILK_C
    )
    if not all(math.isclose(value, target_c) for value in (early_at_target, late_at_target)):
        raise RuntimeError("Target time does not produce the target temperature")
    if args.figure:
        draw(args.figure)
    print(json.dumps({
        "room_c": ROOM_C,
        "coffee_c": COFFEE_C,
        "coffee_mass_kg": COFFEE_MASS_KG,
        "milk_mass_kg": MILK_MASS_KG,
        "specific_heat_j_per_kg_k": SPECIFIC_HEAT,
        "coffee_heat_capacity_j_per_k": round(COFFEE_CAPACITY, 6),
        "mixed_heat_capacity_j_per_k": round(TOTAL_CAPACITY, 6),
        "initial_black_heat_loss_w": round(BLACK_CONDUCTANCE * (COFFEE_C - ROOM_C), 6),
        "initial_mixed_heat_loss_w": round(BLACK_CONDUCTANCE * (initial_mixed - ROOM_C), 6),
        "heat_loss_early_j": round(TOTAL_CAPACITY * (
            initial_mixed - cool(initial_mixed, BLACK_CONDUCTANCE, TOTAL_CAPACITY, WAIT_SECONDS)
        ), 6),
        "heat_loss_late_j": round(COFFEE_CAPACITY * (
            COFFEE_C - cool(COFFEE_C, BLACK_CONDUCTANCE, COFFEE_CAPACITY, WAIT_SECONDS)
        ), 6),
        "break_even_mixed_conductance_w_per_k": round(break_even, 6),
        "temperature_target": {
            "target_c": target_c,
            "black_before_late_milk_c": round(black_target_c, 6),
            "add_early_minutes": round(early_target_seconds / 60, 6),
            "add_late_minutes": round(late_target_seconds / 60, 6),
        },
        "cases": reports,
    }, indent=2))


if __name__ == "__main__":
    main()
