#!/usr/bin/env python3
"""Top (plan) view of pedestrian-level velocity over the city, code_saturne vs OpenFOAM
side by side. Field = velocity ratio |U|/U_ref at z=0.008 m (model), U_ref=0.7812 m/s.

- OpenFOAM : pre-sampled horizontal cut of the URANS time-averaged field
  L4_nolayer_urans/postProcessing/sampleSurfaceMean/<t>/UMean_pedestrian.raw
  (NOT the steady L4_nolayer/postProcessing/sampleSurface snapshot: that run
  uses a different turbulence closure/regime than the URANS run the
  code_saturne comparison and the probe metrics are drawn from, and mixing
  the two here previously understated the OpenFOAM/code_saturne agreement.)
- code_saturne : slice the EnsightGold volume (TimeAverageU, URANS mean) at z=0.008 m
- buildings : footprint from the STL, drawn as grey polygons on both panels
"""
import os, glob, math
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.style.use("/home/dev/AIJ_Niigata_benchmark/blog_article/AIJ_caseE/latex_style.mplstyle")
from matplotlib.collections import PolyCollection
from scipy.interpolate import griddata
import pyvista as pv
import meshio

import sys
LANG = sys.argv[1] if len(sys.argv) > 1 else "fr"
assert LANG in ("fr", "en"), f"langue inconnue: {LANG!r}"
LAB = {
  "fr": dict(cs="code_saturne (champ moyen)", of="OpenFOAM (champ moyen)",
             xlab=r"$x$ (m, maquette), vent d'Ouest (+x)", ylab=r"$y$ (m, maquette)",
             cbar=r"Rapport de vitesse $|U|/U_\mathrm{ref}$ à $z=2$ m",
             sup=r"AIJ Case E (Niigata) : vent au niveau piéton (secteur W), code_saturne vs OpenFOAM"),
  "en": dict(cs="code_saturne (mean field)", of="OpenFOAM (mean field)",
             xlab=r"$x$ (m, model), West wind (+x)", ylab=r"$y$ (m, model)",
             cbar=r"Velocity ratio $|U|/U_\mathrm{ref}$ at $z=2$ m",
             sup=r"AIJ Case E (Niigata): pedestrian-level wind (sector W), code_saturne vs OpenFOAM"),
}[LANG]

HERE  = os.path.dirname(os.path.abspath(__file__))
U_REF = 0.7812
ZCUT  = 0.008
OF_CASE = os.path.join(HERE, '..', 'L4_nolayer_urans')
CS_CASE = os.path.join(HERE, '..', '..', 'code_saturne', 'code_saturne_L4_nolayer',
                       'CASE', 'RESU')
STL = os.path.join(OF_CASE, 'constant', 'triSurface', 'BD_caseE.stl')

# view window (city core): STL bbox + margin
VIEW = dict(xmin=-0.95, xmax=1.15, ymin=-0.85, ymax=0.85)


def of_points():
    raw = sorted(glob.glob(os.path.join(OF_CASE, 'postProcessing', 'sampleSurfaceMean',
                                         '*', 'UMean_pedestrian.raw')))[-1]
    d = np.loadtxt(raw, comments='#')
    xy = d[:, :2]
    spd = np.linalg.norm(d[:, 3:6], axis=1) / U_REF
    return xy, spd


def cs_points():
    case = sorted(glob.glob(os.path.join(CS_CASE, '*', 'postprocessing',
                                          'RESULTS_FLUID_DOMAIN.case')))[-1]
    mb = pv.read(case)
    vol = None
    for name in mb.keys():
        blk = mb[name]
        if blk is None:
            continue
        names = list(blk.cell_data.keys()) + list(blk.point_data.keys())
        if any('TimeAverageU' == n for n in names) or any(n.endswith('TimeAverageU') for n in names):
            vol = blk; break
    if vol is None:                      # fallback: first block carrying any vector
        vol = mb[0]
    if vol.cell_data:                    # cell -> point so the slice interpolates cleanly
        vol = vol.cell_data_to_point_data()
    key = next(k for k in vol.point_data if k.lower().replace('_', '') in
               ('timeaverageu',) or k == 'TimeAverageU')
    sl = vol.slice(normal='z', origin=(0, 0, ZCUT))
    pts = sl.points[:, :2]
    spd = np.linalg.norm(sl.point_data[key], axis=1) / U_REF
    return pts, spd, os.path.basename(os.path.dirname(os.path.dirname(case)))


def building_polys():
    m = meshio.read(STL)
    tris = np.vstack([c.data for c in m.cells if c.type == 'triangle'])
    P = m.points
    # keep facets that have vertical extent (walls) or sit near ground -> footprint
    polys = [P[t][:, :2] for t in tris]
    return polys


def grid(xy, spd, n=400):
    gx = np.linspace(VIEW['xmin'], VIEW['xmax'], n)
    gy = np.linspace(VIEW['ymin'], VIEW['ymax'], int(n * (VIEW['ymax']-VIEW['ymin'])/(VIEW['xmax']-VIEW['xmin'])))
    GX, GY = np.meshgrid(gx, gy)
    GZ = griddata(xy, spd, (GX, GY), method='linear')
    return GX, GY, GZ


def main():
    of_xy, of_s = of_points()
    cs_xy, cs_s, run = cs_points()
    print(f"OF cut pts={len(of_s)}  CS slice pts={len(cs_s)}  CS run={run}")

    GXo, GYo, GZo = grid(of_xy, of_s)
    GXc, GYc, GZc = grid(cs_xy, cs_s)
    vmax = float(np.nanpercentile(np.concatenate([GZo.ravel(), GZc.ravel()]), 99))
    vmax = max(1.2, round(vmax, 1))
    polys = building_polys()

    fig, axs = plt.subplots(1, 2, figsize=(15, 6.6), sharex=True, sharey=True)
    cf = None
    for ax, (GX, GY, GZ), title in zip(
            axs, [(GXc, GYc, GZc), (GXo, GYo, GZo)],
            [LAB["cs"], LAB["of"]]):
        cf = ax.contourf(GX, GY, GZ, levels=np.linspace(0, vmax, 22), cmap='turbo', extend='max')
        ax.add_collection(PolyCollection(polys, facecolors='0.25', edgecolors='none', zorder=5))
        ax.set_title(title, fontsize=13)
        ax.set_aspect('equal'); ax.set_xlabel(LAB["xlab"])
        ax.set_xlim(VIEW['xmin'], VIEW['xmax']); ax.set_ylim(VIEW['ymin'], VIEW['ymax'])
    axs[0].set_ylabel(LAB["ylab"])
    cb = fig.colorbar(cf, ax=axs, fraction=0.025, pad=0.02)
    cb.set_label(LAB["cbar"])
    fig.suptitle(LAB["sup"], fontsize=14, y=0.98)
    out = os.path.join(HERE, f'topview_cs_vs_of_{LANG}.png')
    fig.savefig(out, dpi=140, bbox_inches='tight')
    print('written:', out)


if __name__ == '__main__':
    main()
