import os
from pathlib import Path

# --8<-- [start:code]
"""Thermal barrier coating: two bodies, two mesh resolutions, one solve, checked against series resistance."""

import numpy as np

import jno

run = jno.setup(__file__)
K_SUB, K_FILM = 20.0, 1.0  # metal substrate and ceramic coating conductivity
L_SUB, L_FILM, Q = 1.0, 0.05, 1.0  # thicknesses and the flux injected at the top
H_SUB, H_FILM = 0.12, 0.0125  # one mesh size per body: the coating needs ~4 elements through its thickness

d = jno.shape.regions(
    substrate=jno.shape.rect(0, 0, 1, L_SUB, size=H_SUB),
    coating=jno.shape.rect(0, L_SUB, 1, L_SUB + L_FILM, size=H_FILM),
    conforming=False,  # no fragment: each body keeps its own mesh and the shared surface exists twice
).domain()
T = d.unknown()
phi = T.test()
on_interface = lambda x, y: np.abs(y - L_SUB) < 1e-9


def body(name):  # T and the test function on one body's cells
    x, y, _ = d.variable(name, split=True)
    return T.bind(x=x, y=y), phi.bind(x=x, y=y)


(Ts, ps), (Tc, pc) = body("substrate"), body("coating")
fine = d.variable("film_face", where=on_interface, region="coating", split=True)  # the secondary: the finer side
main = d.variable("base_face", where=on_interface, region="substrate", split=True)
xt, yt, _ = d.variable("top", split=True)

fem = jno.fem(
    [
        K_SUB * (Ts.x * ps.x + Ts.y * ps.y),  # steady conduction in each body
        K_FILM * (Tc.x * pc.x + Tc.y * pc.y),
        -Q * phi.bind(x=xt, y=yt),  # flux in at the top
        T(*fine) - T(*main),  # the tie, a mortar constraint between the two node layouts
        T(*d.variable("bottom", split=True)) - 0.0,
    ]
)
sol = np.asarray(fem.solve()).reshape(-1)
pts = np.asarray(fem.points)

exact_iface, exact_top = Q * L_SUB / K_SUB, Q * L_SUB / K_SUB + Q * L_FILM / K_FILM
got_iface = float(sol[np.abs(pts[:, 1] - L_SUB) < 1e-6].mean())  # fem.points is float32: a 1e-6 band, not 1e-9
got_top = float(sol[pts[:, 1] > L_SUB + L_FILM - 1e-6].mean())
print(f"Coating (tied, two mesh resolutions): dofs={fem.dofs}")
print(f"  T at interface  FEM={got_iface:.5f}  exact={exact_iface:.5f}")
print(f"  T at top        FEM={got_top:.5f}  exact={exact_top:.5f}")
print(f"  the 0.05-thick coating carries {100 * (got_top - got_iface) / got_top:.0f}% of the temperature rise")
assert abs(got_iface - exact_iface) < 0.02 * exact_top and abs(got_top - exact_top) < 0.02 * exact_top  # series resistance
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "tied_coating_multiscale.npz",
        points=pts,
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        T=sol,
        geometry=[L_SUB, L_FILM],
    )
