"""Compare ideal capillary penetration and vertical rise without inertia."""

import argparse
import json
import math
import platform
from pathlib import Path

SURFACE_TENSION = 0.07274  # N/m; IAPWS table at 20 °C
VISCOSITY = 0.001  # Pa s; rounded teaching value for water
DENSITY = 1000.0  # kg/m³; rounded teaching value for water
GRAVITY = 9.81  # m/s²
RADII_MM = (0.10, 0.20, 0.40)
TARGET_M = 0.050


def model_parameters(radius, contact_angle_deg):
    """Return equilibrium height H and viscous coefficient A in SI units."""
    if radius <= 0 or not 0 <= contact_angle_deg <= 90:
        raise ValueError("Use a positive radius and a contact angle from 0 to 90°.")
    cosine = 0.0 if contact_angle_deg == 90 else math.cos(math.radians(contact_angle_deg))
    height = 2 * SURFACE_TENSION * cosine / (DENSITY * GRAVITY * radius)
    coefficient = radius * SURFACE_TENSION * cosine / (4 * VISCOSITY)
    return height, coefficient


def horizontal_distance(seconds, coefficient):
    return math.sqrt(2 * coefficient * seconds)


def rise_integral(fraction):
    """Evaluate the integral of x/(1-x) from 0 to fraction."""
    if fraction < 1e-4:
        # The first four terms avoid cancellation near zero.
        return sum(fraction ** power / power for power in range(2, 6))
    return -fraction - math.log1p(-fraction)


def time_at_height(rise, equilibrium, coefficient):
    """Return seconds for a reachable height, or None for no finite time."""
    if rise == 0:
        return 0.0
    if rise >= equilibrium:
        return None
    return equilibrium ** 2 / coefficient * rise_integral(rise / equilibrium)


def height_at_time(seconds, equilibrium, coefficient):
    if seconds == 0 or equilibrium == 0:
        return 0.0

    low, high = 0.0, 1.0
    scaled_time = seconds * coefficient / equilibrium ** 2
    # The integral is increasing on [0, 1) and diverges at 1.
    for _ in range(55):
        middle = (low + high) / 2
        if middle in (low, high):
            break
        if rise_integral(middle) < scaled_time:
            low = middle
        else:
            high = middle
    return low * equilibrium


def integrate_time(rise, equilibrium, coefficient):
    """Independent composite Simpson check for heights away from the limit."""
    steps = 2048
    width = rise / steps
    total = 0.0
    for i in range(steps + 1):
        position = i * width
        value = position / (coefficient * (1 - position / equilibrium))
        if i in (0, steps):
            weight = 1
        else:
            weight = 4 if i % 2 else 2
        total += weight * value
    return width * total / 3


def describe_radius(radius_mm):
    equilibrium, coefficient = model_parameters(radius_mm / 1000, 0)
    vertical_time = time_at_height(TARGET_M, equilibrium, coefficient)
    if vertical_time is not None:
        check = integrate_time(TARGET_M, equilibrium, coefficient)
        assert math.isclose(vertical_time, check, rel_tol=1e-9)
    vertical_height = height_at_time(1, equilibrium, coefficient)
    assert math.isclose(time_at_height(vertical_height, equilibrium, coefficient), 1, rel_tol=1e-10)
    return {
        "radius_mm": radius_mm,
        "equilibrium_height_mm": round(1000 * equilibrium, 6),
        "horizontal_distance_at_1s_mm": round(1000 * horizontal_distance(1, coefficient), 6),
        "vertical_height_at_1s_mm": round(1000 * vertical_height, 6),
        "horizontal_time_to_50mm_s": round(TARGET_M ** 2 / (2 * coefficient), 6),
        "vertical_time_to_50mm_s": round(vertical_time, 6) if vertical_time is not None else None,
    }


def compare_vertical_targets():
    cases = {}
    for target_mm in (20, 100):
        times = []
        for radius_mm in RADII_MM:
            equilibrium, coefficient = model_parameters(radius_mm / 1000, 0)
            seconds = time_at_height(target_mm / 1000, equilibrium, coefficient)
            times.append(round(seconds, 6) if seconds is not None else None)
        cases[str(target_mm)] = times

    assert cases["20"][2] < cases["20"][1] < cases["20"][0]
    assert cases["100"][0] > 0 and cases["100"][1:] == [None, None]
    return cases


def report():
    h0, a0 = model_parameters(0.0002, 0)
    h60, a60 = model_parameters(0.0002, 60)
    h90, a90 = model_parameters(0.0002, 90)
    rows = [describe_radius(r) for r in RADII_MM]
    assert rows[1]["vertical_time_to_50mm_s"] < rows[0]["vertical_time_to_50mm_s"]
    assert rows[2]["vertical_time_to_50mm_s"] is None
    assert time_at_height(h0, h0, a0) is None
    assert time_at_height(0, h0, a0) == 0.0
    assert math.isclose(h60 / h0, 0.5)
    assert horizontal_distance(1, a90) == height_at_time(1, h90, a90) == 0.0
    return {
        "environment": {
            "macOS": platform.mac_ver()[0] or None,
            "machine": platform.machine(),
            "python": platform.python_version(),
        },
        "surface_tension_n_m": SURFACE_TENSION,
        "viscosity_pa_s": VISCOSITY,
        "density_kg_m3": DENSITY,
        "gravity_m_s2": GRAVITY,
        "main_contact_angle_deg": 0,
        "results": rows,
        "vertical_times_s_by_target_mm_in_radius_order": compare_vertical_targets(),
        "upper_radius_limit_for_reaching_50mm_mm": round(
            1000 * 2 * SURFACE_TENSION / (DENSITY * GRAVITY * TARGET_M), 6
        ),
        "middle_radius_checks": {
            "time_to_90_percent_of_equilibrium_s": round(time_at_height(0.90 * h0, h0, a0), 6),
            "time_to_99_percent_of_equilibrium_s": round(time_at_height(0.99 * h0, h0, a0), 6),
            "time_to_exact_equilibrium_s": time_at_height(h0, h0, a0),
            "equilibrium_at_60_deg_mm": round(1000 * h60, 6),
            "horizontal_distance_at_1s_60_deg_mm": round(1000 * horizontal_distance(1, a60), 6),
            "equilibrium_at_90_deg_mm": round(1000 * h90, 6),
        },
    }


def plot(path):
    """Draw the vertical model curves using optional Matplotlib."""
    from matplotlib import use

    use("Agg")
    from matplotlib import pyplot as plt

    fig, ax = plt.subplots(figsize=(9, 4.6), layout="constrained")
    times = [i / 100 for i in range(401)]
    colors = ("#006678", "#a63e24", "#534c85")
    for radius, color in zip(RADII_MM, colors):
        equilibrium, coefficient = model_parameters(radius / 1000, 0)
        heights = [1000 * height_at_time(t, equilibrium, coefficient) for t in times]
        ax.plot(times, heights, lw=2.5, label=f"Radius {radius:.2f} mm", color=color)
        ax.axhline(equilibrium * 1000, color=color, ls=":", lw=1.4, alpha=0.9)
    ax.axhline(50, color="#505a65", lw=1.2, ls="--")
    ax.text(3.94, 52, "50 mm target", ha="right", va="bottom", color="#414b57")
    ax.set(xlim=(0, 4), ylim=(0, 158), xlabel="Time (s)", ylabel="Rise above the reservoir (mm)")
    ax.set_title("Vertical capillary rise in the viscous model", loc="left", pad=10)
    ax.grid(axis="both", alpha=0.18)
    ax.spines[["top", "right"]].set_visible(False)
    ax.legend(loc="upper right", bbox_to_anchor=(1.0, 0.90), frameon=False,
              title="Dotted lines show equilibrium")
    fig.savefig(path, dpi=160)
    plt.close(fig)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--plot", type=Path, help="write a PNG (requires Matplotlib)")
    args = parser.parse_args()
    result = report()
    if args.plot:
        plot(args.plot)
    print(json.dumps(result, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
