"""Compute the liquid-water dew-point threshold in a defined temperature range."""
import argparse
import json
import math
import platform
import sys
from pathlib import Path

# NIST Chemistry WebBook, Antoine coefficients for water, 273–303 K.
A, B, C = 5.40221, 1838.675, -31.737
MAX_C = 29.85


def saturation_kpa(temp_c):
    if not 0 <= temp_c <= MAX_C:
        raise ValueError("temperature outside the lab range, 0–29.85 °C")
    return 100 * 10 ** (A - B / (temp_c + 273.15 + C))


def vapor_kpa(temp_c, rh_percent):
    if not 0 < rh_percent <= 100:
        raise ValueError("relative humidity must be in (0, 100]")
    return saturation_kpa(temp_c) * rh_percent / 100


def dew_point_c(vapor):
    if not saturation_kpa(0) <= vapor <= saturation_kpa(MAX_C):
        raise ValueError("dew point outside the liquid-water lab range")
    return B / (A - math.log10(vapor / 100)) - C - 273.15


def sample(name, air_c, rh, surface_c):
    vapor = vapor_kpa(air_c, rh)
    surface_vapor = saturation_kpa(surface_c)
    dew = dew_point_c(vapor)
    margin = surface_c - dew
    if math.isclose(margin, 0, abs_tol=1e-9):
        condition = "at_threshold"
    else:
        condition = "below_dew_point" if margin < 0 else "above_dew_point"
    return {
        "case": name, "air_c": round(air_c, 6), "rh_percent": round(rh, 6),
        "vapor_kpa": round(vapor, 6), "surface_c": round(surface_c, 6),
        "surface_saturation_kpa": round(surface_vapor, 6),
        "dew_point_c": round(dew, 6), "surface_minus_dew_point_c": round(margin, 6),
        "condition": condition,
    }


def run():
    baseline_vapor = vapor_kpa(20, 50)
    baseline_dew = dew_point_c(baseline_vapor)
    warmed_rh = 100 * baseline_vapor / saturation_kpa(25)
    rows = [
        sample("baseline_cold_glass", 20, 50, 8),
        sample("baseline_warmer_glass", 20, 50, 12),
        sample("warm_air_same_vapor_pressure", 25, warmed_rh, 8),
        sample("warm_air_same_relative_humidity", 25, 50, 12),
        sample("lower_vapor_pressure", 20, 40, 8),
        sample("warmer_surface_only", 20, 50, 10),
        sample("exact_threshold", 20, 50, baseline_dew),
    ]
    assert [r["condition"] for r in rows] == [
        "below_dew_point", "above_dew_point", "below_dew_point",
        "below_dew_point", "above_dew_point", "above_dew_point", "at_threshold",
    ]
    assert rows[0]["dew_point_c"] == rows[2]["dew_point_c"]
    assert math.isclose(dew_point_c(vapor_kpa(20, 100)), 20, abs_tol=1e-9)
    assert math.isclose(saturation_kpa(baseline_dew), baseline_vapor, abs_tol=1e-12)
    for temp, humidity, surface in ((20, 0, 8), (20, 101, 8), (20, 20, 8),
                                    (30, 50, 8), (20, 50, -1)):
        try:
            sample("outside_scope", temp, humidity, surface)
        except ValueError:
            pass
        else:
            raise AssertionError("input outside the model range accepted")

    # Independent input intervals, not a probability distribution.
    dew_low = dew_point_c(vapor_kpa(19.5, 47))
    dew_high = dew_point_c(vapor_kpa(20.5, 53))
    min_margin, max_margin = 9.0 - dew_high, 10.0 - dew_low
    assert min_margin < 0 < max_margin
    temp_only = [dew_point_c(vapor_kpa(t, 50)) for t in (19.5, 20.5)]
    humidity_only = [dew_point_c(vapor_kpa(20, rh)) for rh in (47, 53)]
    for low, high in (temp_only, humidity_only):
        assert dew_low < low < baseline_dew < high < dew_high
    outdoor_cold = vapor_kpa(5, 90)
    outdoor_warm = vapor_kpa(25, 45)
    assert outdoor_cold < baseline_vapor < outdoor_warm
    assert baseline_vapor < saturation_kpa(12) < outdoor_warm
    return {
        "environment": {
            "os": platform.system(), "os_version": platform.mac_ver()[0] or platform.release(),
            "machine": platform.machine(), "python": sys.version.split()[0],
        },
        "model": {"antoine": [A, B, C], "temperature_c": [0, MAX_C]},
        "scenarios": rows,
        "threshold_room_rh_at_20_c_percent": {
            str(t): round(100 * saturation_kpa(t) / saturation_kpa(20), 6) for t in (8, 12)
        },
        "interval_example": {
            "air_c": [19.5, 20.5], "rh_percent": [47, 53], "surface_c": [9, 10],
            "dew_point_c": [round(dew_low, 6), round(dew_high, 6)],
            "dew_point_varying_air_temp_only_c": [round(t, 6) for t in temp_only],
            "dew_point_varying_rh_only_c": [round(t, 6) for t in humidity_only],
            "surface_minus_dew_point_c": [round(min_margin, 6), round(max_margin, 6)],
        },
        "air_comparison_kpa": {
            "outdoor_5c_90rh": round(outdoor_cold, 6),
            "indoor_20c_50rh": round(baseline_vapor, 6),
            "outdoor_25c_45rh": round(outdoor_warm, 6),
        },
        "outside_scope_cases_rejected": 5,
    }


def diagram():
    vapor = vapor_kpa(20, 50)
    dew = dew_point_c(vapor)
    def x(temp):
        return 104 + temp * 28
    def y(pressure):
        return 409 - pressure * 86
    curve = " ".join(f"{x(i/4):.2f},{y(saturation_kpa(i/4)):.2f}" for i in range(105))
    x_ticks = "".join(
        f'<line x1="{x(t)}" y1="409" x2="{x(t)}" y2="415" class="axis"/>'
        f'<text x="{x(t)}" y="437" class="tick" text-anchor="middle">{t}</text>'
        for t in (0, 5, 10, 15, 20, 25)
    )
    y_ticks = "".join(
        f'<line x1="104" y1="{y(p)}" x2="832" y2="{y(p)}" class="grid"/>'
        f'<text x="88" y="{y(p)+5}" class="tick" text-anchor="end">{p:g}</text>'
        for p in (0, .5, 1, 1.5, 2, 2.5, 3, 3.5)
    )
    return f'''<svg xmlns="http://www.w3.org/2000/svg" width="940" height="492" viewBox="0 0 940 492" role="img" aria-labelledby="title desc">
<title id="title">Window surface temperature and dew point</title>
<desc id="desc">Saturation vapor pressure rises with temperature. The room vapor pressure at 20 degrees Celsius and 50 percent relative humidity crosses the saturation curve near 9.3 degrees. Eight degrees is below the threshold, and twelve degrees is above it.</desc>
<style>
text{{font-family:system-ui,sans-serif;fill:#122a43}}.title{{font-size:27px;font-weight:700}}.label{{font-size:16px;font-weight:600}}.tick{{font-size:15px}}.axis{{stroke:#263f55;stroke-width:1.5}}.grid{{stroke:#dce6ee;stroke-width:1}}.curve{{stroke:#155ca8;stroke-width:3;fill:none}}.vapor{{stroke:#007662;stroke-width:2.4;stroke-dasharray:8 5}}
</style>
<rect width="940" height="492" fill="#fff"/>
<text x="43" y="43" class="title">Where a window reaches the dew point</text>
<text x="104" y="90" class="label">Vapor pressure (kPa)</text>
<rect x="104" y="108" width="{x(dew)-104:.2f}" height="301" fill="#fff2e9"/>
{y_ticks}
<path d="M104 108 V409 H832" class="axis" fill="none"/>
{x_ticks}
<polyline points="{curve}" class="curve"/>
<line x1="104" y1="{y(vapor):.2f}" x2="832" y2="{y(vapor):.2f}" class="vapor"/>
<line x1="{x(dew):.2f}" y1="{y(vapor):.2f}" x2="{x(dew):.2f}" y2="409" stroke="#a74826" stroke-dasharray="4 4"/>
<circle cx="{x(dew):.2f}" cy="{y(vapor):.2f}" r="5" fill="#a74826"/>
<path d="M 271 248 L {x(dew)-5:.2f} {y(vapor)-6:.2f}" fill="none" stroke="#a74826" stroke-width="1.4"/>
<text x="133" y="243" class="label">Dew point {dew:.2f} °C</text>
<circle cx="{x(8)}" cy="{y(saturation_kpa(8)):.2f}" r="5" fill="#a74826"/>
<circle cx="{x(12)}" cy="{y(saturation_kpa(12)):.2f}" r="5" fill="#155ca8"/>
<text x="{x(8)-13}" y="{y(saturation_kpa(8))+25:.2f}" class="label" text-anchor="end">8 °C</text>
<text x="{x(12)+9}" y="{y(saturation_kpa(12))-10:.2f}" class="label">12 °C</text>
<line x1="532" y1="63" x2="567" y2="63" class="curve"/>
<text x="577" y="68" class="label">Liquid-water saturation</text>
<line x1="532" y1="87" x2="567" y2="87" class="vapor"/>
<text x="577" y="92" class="label">Room air: 20 °C, RH 50%</text>
<text x="468" y="470" class="label" text-anchor="middle">Surface temperature (°C)</text>
</svg>
'''


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--svg", type=Path, help="write the computed diagram")
    args = parser.parse_args()
    report = run()
    if args.svg:
        args.svg.write_text(diagram(), encoding="utf-8")
    print(json.dumps(report, indent=2, ensure_ascii=False))
