"""Step 3 (second method). Finite-difference solution of the Dirichlet problem [B] eq. (6-dirichlet) on the slit strip.

No conformal map and no closed form is used: we solve Laplace's equation on the quarter strip 0<x<X, 0<y<1/2 with
    U = 0                         on the edge y = 1/2,
    U = -(2 pi/3) x               on the slit  y = 0, x >= s,
    dU/dy = 0                     on y = 0, x < s      (symmetry b -> conj b),
    dU/dx = 0                     on x = 0             (symmetry b -> -b),
    U = -(2 pi/3) X (1 - 2y)      at x = X  (the exact harmonic function with the slit/edge data; corrections ~ e^{-2 pi (X-s)}).
The tip is placed half-way between two grid nodes. Grids are refined and Richardson-extrapolated.

Compared with: closed form of Lemma 6.5 (s = x*), the Poisson integral of s02 (general s).
Outputs: results/fd_convergence.csv, results/fd_axes.csv, results/fd_field_xstar.npz, results/fd_summary.json
"""
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla
import mpmath as mp
from common import Tee, event, save_json, save_csv, RES
import os, time

XS = float(mp.asinh(1) / mp.pi)
TWO_PI_3 = 2 * np.pi / 3


def solve_fd(s, Ny, X=2.5):
    hy = 0.5 / Ny
    k = max(1, int(round(s / hy - 0.5)))          # nodes 0..k are free on y=0; tip at (k+1/2) hx
    hx = s / (k + 0.5)
    Nx = int(round(X / hx)); X = Nx * hx
    idx = -np.ones((Nx + 1, Ny + 1), dtype=np.int64)
    n = 0
    for i in range(Nx):
        j0 = 0 if i <= k else 1
        for j in range(j0, Ny):
            idx[i, j] = n; n += 1
    xg = np.arange(Nx + 1) * hx; yg = np.arange(Ny + 1) * hy

    def dirichlet(i, j):
        if j == Ny:
            return 0.0
        if i == Nx:
            return -TWO_PI_3 * X * (1 - 2 * yg[j])
        return -TWO_PI_3 * xg[i]                    # slit node (j == 0, i > k)
    rows, cols, vals = [], [], []
    rhs = np.zeros(n)
    ax, ay = 1.0 / hx**2, 1.0 / hy**2
    for i in range(Nx):
        j0 = 0 if i <= k else 1
        for j in range(j0, Ny):
            r = idx[i, j]
            rows.append(r); cols.append(r); vals.append(-2 * ax - 2 * ay)
            for (ii, jj, w) in ((i + 1, j, ax), (i - 1, j, ax), (i, j + 1, ay), (i, j - 1, ay)):
                if ii < 0:
                    ii = 1                          # Neumann mirror at x = 0
                if jj < 0:
                    jj = 1                          # Neumann mirror at y = 0 (only reached for i <= k)
                q = idx[ii, jj]
                if q >= 0:
                    rows.append(r); cols.append(q); vals.append(w)
                else:
                    rhs[r] -= w * dirichlet(ii, jj)
    A = sp.csr_matrix((vals, (rows, cols)), shape=(n, n))
    u = spla.spsolve(A.tocsc(), rhs)
    U = np.zeros((Nx + 1, Ny + 1))
    for i in range(Nx + 1):
        for j in range(Ny + 1):
            U[i, j] = u[idx[i, j]] if idx[i, j] >= 0 else dirichlet(i, j)
    return xg, yg, U, k, hx, hy


def closed_form_axes():
    mp.mp.dps = 30
    xs = mp.asinh(1) / mp.pi
    asn = lambda s: mp.asin(min(mp.sinh(mp.pi * s), mp.mpf(1)))
    U0 = -2 * mp.pi * xs / 3 + mp.mpf(4) / 3 * mp.quad(asn, [0, xs])
    Ux = lambda x: float(U0 - mp.mpf(4) / 3 * mp.quad(asn, [0, x]))
    Uy = lambda y: float(U0 + mp.mpf(4) / 3 * mp.quad(lambda s: mp.asinh(mp.sin(mp.pi * s)), [0, y]))
    return float(U0), Ux, Uy


def tip_coefficient(xg, U0row, s, k):
    """Least-squares fit (U+L)(x) = g sqrt(s-x) + c1 (s-x) + c2 (s-x)^1.5 on 0.01 <= s-x <= 0.08."""
    d = s - xg[: k + 1]
    m = (d >= 0.01) & (d <= 0.08)
    y = U0row[: k + 1][m] + TWO_PI_3 * xg[: k + 1][m]
    B = np.vstack([np.sqrt(d[m]), d[m], d[m] ** 1.5]).T
    coef, *_ = np.linalg.lstsq(B, y, rcond=None)
    return coef[0]


def main():
    U0_exact, Ux, Uy = closed_form_axes()
    import csv
    gt = {round(float(r["s"]), 4): r for r in csv.DictReader(open(os.path.join(RES, "gamma_tip.csv")))}
    summ = {"x_star": XS, "U0_closed_form": U0_exact}
    print("== convergence at s = x* against the closed form of [B] Lemma 6.5")
    conv = []
    sols = {}
    for Ny in (50, 100, 200, 400):
        t0 = time.time()
        xg, yg, U, k, hx, hy = solve_fd(XS, Ny)
        sols[Ny] = (xg, yg, U, k)
        ex = np.array([Ux(x) for x in xg[: k + 1 : max(1, (k + 1) // 25)]])
        fx = U[: k + 1 : max(1, (k + 1) // 25), 0]
        ey = np.array([Uy(y) for y in yg[:: max(1, Ny // 25)]])
        fy = U[0, :: max(1, Ny // 25)]
        conv.append([Ny, hx, hy, U.size, U[0, 0], U[0, 0] - U0_exact, float(np.max(np.abs(fx - ex))), float(np.max(np.abs(fy - ey))), time.time() - t0])
        print(f"  Ny={Ny:4d} hx={hx:.5f}: U(0)={U[0,0]:+.6f} (closed form {U0_exact:+.6f}, err {U[0,0]-U0_exact:+.2e}); "
              f"max err real axis {conv[-1][6]:.2e}, imaginary axis {conv[-1][7]:.2e}; {conv[-1][8]:.1f}s")
    save_csv("fd_convergence.csv", ["Ny", "hx", "hy", "n_nodes", "U_at_0", "err_U0", "max_err_real_axis", "max_err_imag_axis", "seconds"], conv)
    e = [abs(c[5]) for c in conv]
    orders = [float(np.log2(e[i] / e[i + 1])) for i in range(len(e) - 1)]
    rich = conv[-1][4] + (conv[-1][4] - conv[-2][4]) / (2 ** orders[-1] - 1)
    print(f"  observed convergence orders of U(0): {[round(o,2) for o in orders]}; Richardson value {rich:+.6f} (closed form {U0_exact:+.6f})")
    summ.update(orders=orders, U0_richardson=rich, U0_fd_finest=conv[-1][4], err_finest=conv[-1][5], max_err_real_axis_finest=conv[-1][6], max_err_imag_axis_finest=conv[-1][7])
    xg, yg, U, k = sols[200]
    np.savez_compressed(os.path.join(RES, "fd_field_xstar.npz"), x=xg[xg <= 1.2], y=yg, U=U[xg <= 1.2, :])
    rows = [[float(x), float(U[i, 0]), Ux(float(x)), float(U[i, 0]) - Ux(float(x))] for i, x in enumerate(xg[: k + 1])]
    save_csv("fd_axes.csv", ["x", "U_fd", "U_closed_form", "diff"], rows)

    print("== general slit s: FD against the Poisson integral of s02, and the sign change of the tip coefficient")
    out = []
    for s in (0.24, 0.26, 0.27, XS, 0.29, 0.30, 0.32):
        xg, yg, U, k, hx, hy = solve_fd(s, 200)
        g = tip_coefficient(xg, U[:, 0], s, k)
        ref = gt.get(round(s, 4))
        mx = float(np.max(U[: k + 1, 0] + TWO_PI_3 * xg[: k + 1]))
        out.append([s, U[0, 0], float(ref["U_s_at_0"]) if ref else "", g, float(ref["gamma_tip"]) if ref else "", mx])
        print(f"  s={s:.4f}: U_s(0) FD {U[0,0]:+.6f}  Poisson {float(ref['U_s_at_0']):+.6f} | tip coeff FD {g:+.4f}  Poisson {float(ref['gamma_tip']):+.4f} | max(U_s+L) on nodes {mx:+.5f}")
    save_csv("fd_general_s.csv", ["s", "U0_fd", "U0_poisson", "gamma_tip_fd", "gamma_tip_poisson", "max_Us_plus_L_fd"], out)
    ss = np.array([o[0] for o in out]); gg = np.array([o[3] for o in out])
    i = np.where(np.sign(gg[:-1]) != np.sign(gg[1:]))[0]
    lin = np.polyfit(ss, gg, 1)
    s_root = -lin[1] / lin[0]
    print(f"  FD tip coefficient changes sign between s={ss[i[0]]:.4f} and s={ss[i[0]+1]:.4f}; linear fit root s = {s_root:.4f} (x* = {XS:.4f})" if len(i) else "  no sign change found")
    summ.update(s_root_fd=float(s_root), max_abs_U0_diff_fd_poisson=float(max(abs(o[1] - o[2]) for o in out)),
                max_abs_gamma_diff_fd_poisson=float(max(abs(o[3] - o[4]) for o in out)))
    save_json("fd_summary.json", summ)
    event("validate", "Finite-difference Laplace solve on the slit strip (second method)",
          f"U(0) FD(Richardson) {rich:+.6f} vs closed form {U0_exact:+.6f}; FD tip-coefficient root s={s_root:.4f} vs x*={XS:.4f}",
          outputs=["results/fd_convergence.csv", "results/fd_general_s.csv"])


if __name__ == "__main__":
    with Tee("s03_dirichlet_fd"):
        main()
