"""
Basement wall moisture over Swedish years: XPS drainage board vs a vapour-open
bead board (Isodran/Pordran type) on the outside of an old concrete wall.

1D moisture transport through the concrete (Kunzel-type formulation with
relative humidity as driving potential, as in WUFI), with a quasi-steady
temperature profile recomputed every hour from seasonal soil and indoor
climate. No transient heat storage or latent-heat coupling. A screening model
with typical material data, not a validated WUFI/Delphin calculation.

Mechanisms included:
- vapour diffusion in both directions through each layer (net from high to low
  vapour pressure, which depends on temperature and humidity);
- capillary (liquid) transport inside the concrete;
- inward drying to the basement through the interior finish;
- moisture supply from below (rising damp) as a source in the wall;
- liquid water reaching the wall face during wet periods, given as equivalent
  full-contact days per year (a sensitivity parameter for either board).
Water that cannot enter a saturated wall is booked as overflow, so the mass
balance closes.
"""

import json
import sys

import numpy as np
from scipy.linalg import solve_banded

YEAR = 365 * 24 * 3600.0
DELTA_A = 2.0e-10  # kg/(m s Pa), vapour permeability of still air
BETA_IN = 2.5e-8  # kg/(m2 s Pa), interior surface vapour transfer


def psat(T):
    T = np.asarray(T, dtype=float)
    water = 610.5 * np.exp(17.269 * T / (237.3 + T))
    ice = 610.5 * np.exp(21.875 * T / (265.5 + T))
    return np.where(T >= 0, water, ice)


# Old, fairly porous concrete (typical database values)
WF, B = 150.0, 1.2  # free saturation kg/m3; isotherm shape gives w80 = 60 kg/m3
MU_C, LAM_C, A_C = 70.0, 1.6, 0.02  # vapour resistance, W/mK, kg/(m2 s^0.5)
D_WALL, N = 0.20, 40
DX = D_WALL / N
DELTA_C = DELTA_A / MU_C
PHI_CONTACT = 0.995  # wall face in contact with liquid water


def w_of(phi):
    return WF * (B - 1) * phi / (B - phi)


def dw_dphi(phi):
    return WF * (B - 1) * B / (B - phi) ** 2


def d_suction(w):
    return 3.8 * (A_C / WF) ** 2 * 1000.0 ** (w / WF - 1.0)


def d_redistribution(w):
    return d_suction(w) / 10.0


BOARDS = {
    "xps": {"mu": 150.0, "lam": 0.036, "d": 0.10},  # Finnfoam XPS300 DoP
    "open": {"mu": 4.4, "lam": 0.042, "d": 0.10},  # SINTEF rapport 84 / Isodran 60
}


def climate(t, depth, heated):
    day = t / 86400.0
    om = 2 * np.pi / 365.0
    T_out = 7.0 + 9.0 * np.cos(om * (day - 200))  # Swedish coastal-ish, max late July
    rh_out = 0.80 + 0.08 * np.cos(om * (day - 355))  # damper in winter
    p_out = rh_out * psat(T_out)
    dd = 2.5  # m, damping depth of the annual soil wave
    T_soil = 9.0 + 9.0 * np.exp(-depth / dd) * np.cos(om * (day - 200) - depth / dd)
    if heated:
        T_in = 20.0
        p_in = min(p_out + 250.0, 0.9 * psat(T_in))
    else:
        T_in = 9.0 + 5.0 * np.cos(om * (day - 215))
        p_in = min(p_out + 100.0, 0.95 * psat(T_in))
    return T_in, float(p_in), float(T_soil)


def contact_days(n_per_year):
    """Spread equivalent full-contact days over snowmelt, autumn rain and summer storms."""
    if n_per_year <= 0:
        return set()
    windows = [(95, 125, 0.4), (280, 330, 0.4), (180, 240, 0.2)]
    raw = [n_per_year * share for _, _, share in windows]
    counts = [int(r) for r in raw]
    # largest remainder, so the counts add up to n_per_year
    for i in sorted(range(len(raw)), key=lambda i: raw[i] - counts[i], reverse=True):
        if sum(counts) >= n_per_year:
            break
        counts[i] += 1
    days = set()
    for (start, end, _), k in zip(windows, counts):
        if k:
            days.update(int(d) for d in np.linspace(start, end, k + 2)[1:-1])
    return days


def simulate(board, depth=2.0, heated=True, sd_in=0.1, rising=0.0, wet_days=0,
             phi0=0.95, years=10, dt=3600.0, r_int=0.0):
    b = BOARDS[board]
    z_out = b["mu"] * b["d"] / DELTA_A + (DX / 2) / DELTA_C
    z_in = sd_in / DELTA_A + 1.0 / BETA_IN + (DX / 2) / DELTA_C
    r_ins = b["d"] / b["lam"]
    x = (np.arange(N) + 0.5) * DX
    source = rising / (D_WALL * YEAR)  # kg/(m3 s)
    phi = np.full(N, phi0)
    w = w_of(phi)
    wet = contact_days(wet_days)
    steps_per_year = int(YEAR / dt)
    out = {"w_mean": [float(w.mean())], "inward": [], "outward": [], "uptake": [],
           "phi_inner": [], "phi_outer": [], "overflow": [],
           "rh_in50_end": [], "rh_out50_end": []}
    acc_in = acc_out = acc_up = acc_over = 0.0
    inner_hist, outer_hist = [], []
    for step in range(years * steps_per_year):
        t = (step % steps_per_year) * dt
        T_in, p_in, T_soil = climate(t, depth, heated)
        r_tot = 0.13 + r_int + D_WALL / LAM_C + r_ins
        q = (T_in - T_soil) / r_tot
        T_ci = T_in - q * (0.13 + r_int)
        T = T_ci - q * (D_WALL / LAM_C) * (x / D_WALL)
        ps = psat(T)
        p_soil = float(psat(T_soil))
        contact = int(t // 86400) in wet
        w_n = w.copy()
        kc_used = 0.0
        for _ in range(25):
            C = dw_dphi(phi)
            wk = w_of(phi)
            Dl = d_redistribution(wk) * C
            K = 0.5 * (Dl[:-1] + Dl[1:]) / DX  # liquid conductance between nodes
            G = DELTA_C / DX
            diag = DX * C / dt
            rhs = DX * (w_n - wk + C * phi) / dt + source * DX
            lower = np.zeros(N)
            upper = np.zeros(N)
            # interior faces
            diag[:-1] += K + G * ps[:-1]
            upper[1:] = -(K + G * ps[1:])
            diag[1:] += K + G * ps[1:]
            lower[:-1] = -(K + G * ps[:-1])
            # room side
            diag[0] += ps[0] / z_in
            rhs[0] += p_in / z_in
            # soil side
            if contact:
                kc = d_suction(0.5 * (wk[-1] + WF)) * dw_dphi(0.99) / (DX / 2)
                kc_used = kc
                diag[-1] += kc
                rhs[-1] += kc * PHI_CONTACT
            else:
                diag[-1] += ps[-1] / z_out
                rhs[-1] += p_soil / z_out
            ab = np.vstack([upper, diag, lower])
            new = solve_banded((1, 1), ab, rhs)
            new = np.clip(new, 0.05, 1.15)
            if np.max(np.abs(new - phi)) < 1e-9:
                phi = new
                break
            phi = new
        over = np.clip(phi, None, 1.15) > 1.0
        if over.any():
            acc_over += float((w_of(phi[over]) - WF).sum() * DX)
            phi = np.minimum(phi, 1.0)
        w = w_of(phi)
        g_in = (ps[0] * phi[0] - p_in) / z_in * dt  # kg/m2 leaving to room
        if contact:
            g_out = -kc_used * (PHI_CONTACT - phi[-1]) * dt
        else:
            g_out = (ps[-1] * phi[-1] - p_soil) / z_out * dt
        acc_in += g_in
        acc_out += max(g_out, 0.0)
        acc_up += max(-g_out, 0.0)
        inner_hist.append(phi[:4].mean())
        outer_hist.append(phi[-4:].mean())
        if (step + 1) % steps_per_year == 0:
            out["w_mean"].append(float(w.mean()))
            out["inward"].append(acc_in)
            out["outward"].append(acc_out)
            out["uptake"].append(acc_up)
            out["phi_inner"].append(float(np.mean(inner_hist)))
            out["phi_outer"].append(float(np.mean(outer_hist)))
            out["overflow"].append(acc_over)
            zone = max(1, int(round(0.05 / DX)))
            out["rh_in50_end"].append(float(phi[:zone].mean()))
            out["rh_out50_end"].append(float(phi[-zone:].mean()))
            acc_in = acc_out = acc_up = acc_over = 0.0
            inner_hist, outer_hist = [], []
    return out


if __name__ == "__main__":
    args = json.loads(sys.argv[1]) if len(sys.argv) > 1 else {}
    print(json.dumps(simulate(**args)))
