"""Reproduce the thin-mask teaching experiment and its figures.

From the article's asset directory:
    uv run --script simulate.py
"""

# /// script
# requires-python = ">=3.12"
# dependencies = ["numpy==2.5.5", "matplotlib==3.11.2"]
# ///

import csv
import json
from pathlib import Path

import matplotlib
import numpy as np

matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle


OUTPUT = Path(__file__).resolve().parent
PITCHES = {"Dense line": 1.20, "Isolated-line proxy": 6.00}
TARGET = 0.52
CD_TOL = 0.026
THRESHOLD = 0.25
SIGMA = 0.65
WIDTHS = np.linspace(0.34, 0.57, 461)
TRAIN_FOCUS = np.linspace(-0.32, 0.32, 5)
FOCUS = np.linspace(-0.65, 0.65, 261)
DOSE = np.linspace(0.80, 1.20, 81)
BAND_EL = 0.03  # half width, relative to D0
POLICIES = ("Nominal-only", "Through-process")
DENSE = "#24559b"
ISOLATED = "#9d4b1f"
COMMON = "#086960"
INK = "#263647"


def diffraction_orders(pitch):
    last = int(np.floor((1 + SIGMA) * pitch))
    return np.arange(-last, last + 1) / pitch


def aerial_image(pitch, widths, focus, x):
    """Exact slit-source integration of the finite transmitted order pairs."""
    f = diffraction_orders(pitch)
    left, right = f[:, None], f[None, :]
    lower = np.maximum(-SIGMA, np.maximum(-1 - left, -1 - right))
    upper = np.minimum(SIGMA, np.minimum(1 - left, 1 - right))
    length = np.maximum(0, upper - lower)
    center = (upper + lower) / 2
    delta = left - right
    z = focus[:, None, None]
    phase = -np.pi * z * delta * (left + right + 2 * center)
    coupling = length / (2 * SIGMA) * np.sinc(z * delta * length) * np.exp(1j * phase)
    mask = widths[:, None] / pitch * np.sinc(widths[:, None] * f)
    weights = coupling[None, ...] * (mask[:, :, None] * mask[:, None, :])[:, None, ...]
    waves = np.exp(2j * np.pi * delta.ravel()[:, None] * x)
    return (weights.reshape(len(widths), len(focus), -1) @ waves).real


def source_point_reference(pitch, width, focus, x):
    """Independent Abbe sum, with each hard-pupil transition split explicitly."""
    f = diffraction_orders(pitch)
    breaks = np.r_[-SIGMA, SIGMA, -1 - f, 1 - f]
    breaks = np.unique(np.clip(breaks, -SIGMA, SIGMA))
    nodes, weights = np.polynomial.legendre.leggauss(12)
    result = np.zeros((len(focus), len(x)))
    for low, high in zip(breaks[:-1], breaks[1:]):
        s = (high + low) / 2 + (high - low) / 2 * nodes
        g = s[:, None] + f
        pupil = (np.abs(g) <= 1) * np.exp(-1j * np.pi * focus[:, None, None] * g**2)
        mask = width / pitch * np.sinc(width * f)
        field = (pupil * mask) @ np.exp(2j * np.pi * f[:, None] * x)
        result += (high - low) / (4 * SIGMA) * np.einsum(
            "s,zsx->zx", weights, np.abs(field)**2
        )
    return result


def acceptance_boundaries(pitch, widths, focus):
    gauges = (TARGET + np.array([-CD_TOL, CD_TOL])) / 2
    return THRESHOLD / aerial_image(pitch, widths, focus, gauges)


def choose_mask_widths(pitch):
    # Locate the width that places the edge at the nominal target.
    nominal = aerial_image(pitch, WIDTHS, np.array([0.0]), np.array([TARGET / 2]))
    nominal_index = np.argmin(np.abs(nominal[:, 0, 0] - THRESHOLD))

    # At the same five focus cuts, maximize the symmetric dose band around D0.
    limits = acceptance_boundaries(pitch, WIDTHS, TRAIN_FOCUS)
    exit_low = 1 - np.max(limits[:, :, 0], axis=1)
    exit_high = np.min(limits[:, :, 1], axis=1) - 1
    robust_index = np.argmax(np.minimum(exit_low, exit_high))
    return WIDTHS[[nominal_index, robust_index]]


def printed_cd(pitch, widths, points):
    """First-edge interpolation where exactly one bright-center crossing exists."""
    x = np.linspace(0, pitch / 2, points)
    intensity = aerial_image(pitch, widths, FOCUS, x)
    cd = np.full((len(widths), len(FOCUS), len(DOSE)), np.nan)
    for width_index, image in enumerate(intensity):
        for focus_index, profile in enumerate(image):
            above = (DOSE[:, None] * profile) >= THRESHOLD
            valid = above[:, 0] & (np.count_nonzero(np.diff(above, axis=1), axis=1) == 1)
            dose_index = np.flatnonzero(valid)
            stop = np.argmax(~above[valid], axis=1)
            start = stop - 1
            fraction = (THRESHOLD / DOSE[dose_index] - profile[start])
            fraction = fraction / (profile[stop] - profile[start])
            cd[width_index, focus_index, dose_index] = 2 * (x[start] + fraction * (x[1] - x[0]))
    return cd


def window_metrics(low, high):
    train_span = np.abs(FOCUS) <= 0.3200000001
    exact_focus = np.flatnonzero(np.isclose(FOCUS, 0))[0]
    allowed = (low <= 1 - BAND_EL) & (high >= 1 + BAND_EL)
    assert allowed[exact_focus]
    end = exact_focus + np.flatnonzero(~allowed[exact_focus:])[0] - 1
    clearance = np.minimum(1 - low, high - 1)
    # On the positive side, interpolate the first crossing of the required band.
    crossing = np.interp(BAND_EL, clearance[end:end + 2][::-1], FOCUS[end:end + 2][::-1])
    widths = np.maximum(0, np.minimum(high, DOSE[-1]) - np.maximum(low, DOSE[0]))
    return {
        "centered_el_at_focus_zero": float(2 * clearance[exact_focus]),
        "centered_el_across_focus_plus_minus_0.32": float(2 * clearance[train_span].min()),
        "centered_dof_at_6_percent_el": float(2 * crossing),
        "area_within_scan": float(np.trapezoid(widths, FOCUS)),
    }


def plot_figures(cases, boundaries, common):
    plt.rcParams.update({
        "font.family": "DejaVu Sans",
        "font.size": 14,
        "axes.spines.top": False,
        "axes.spines.right": False,
        "axes.labelcolor": INK,
        "axes.titlecolor": INK,
        "axes.edgecolor": "#9faebc",
        "text.color": INK,
        "xtick.color": INK,
        "ytick.color": INK,
        "axes.grid": True,
        "grid.color": "#e1e7ea",
        "axes.axisbelow": True,
        "figure.facecolor": "white",
        "legend.frameon": False,
    })

    def save(fig, filename):
        fig.savefig(OUTPUT / filename, dpi=180)
        plt.close(fig)

    fig, axes = plt.subplots(2, 1, figsize=(7.2, 6.65), layout="constrained", sharex=True)
    x = np.linspace(-0.55, 0.55, 301)
    for ax, (name, pitch) in zip(axes, PITCHES.items()):
        width = cases[name]["widths"][0]
        for image, color, style, label in zip(
            aerial_image(pitch, np.array([width]), np.array([0., 0.40]), x)[0],
            (DENSE, ISOLATED), ("-", "--"), ("Focus 0", "Focus +0.40")
        ):
            ax.plot(x, image, lw=2.3, color=color, ls=style, label=label)
        ax.axhline(THRESHOLD, color=INK, lw=1.1, ls=":", label="Threshold at D/D₀ = 1")
        for edge in (-TARGET / 2, TARGET / 2):
            ax.axvline(edge, color="#89949f", lw=1, ls=":")
        ax.set(title=name, ylabel="Relative intensity", ylim=(0, 0.58))
    axes[0].legend(loc="upper right", fontsize=11)
    axes[-1].set_xlabel("Wafer coordinate x (λ/NA)")
    save(fig, "aerial-image.png")

    fig, axes = plt.subplots(2, 1, figsize=(7.2, 6.65), layout="constrained", sharex=True)
    for ax, (name, case) in zip(axes, cases.items()):
        ax.axhspan(-5, 5, color="#e6eeec", label="CD spec")
        for d, color, style in [(0.95, DENSE, "--"), (1.00, COMMON, "-"), (1.05, ISOLATED, "-.")]:
            dose_index = np.flatnonzero(np.isclose(DOSE, d))[0]
            cd_error = (case["cd"][0, :, dose_index] / TARGET - 1) * 100
            ax.plot(FOCUS, cd_error, lw=2.2, ls=style, color=color, label=f"D/D₀ = {d:.2f}")
        ax.axhline(0, color="#89949f", lw=1, ls=":")
        ax.set(title=name, ylabel="CD error (%)", ylim=(-26, 13))
    axes[0].legend(loc="lower center", ncol=2, fontsize=11)
    axes[-1].set_xlabel("Defocus f (λ/NA²)")
    save(fig, "bossung.png")

    fig, axes = plt.subplots(2, 1, figsize=(7.2, 7.25), layout="constrained", sharex=True)
    for index, (policy, ax) in enumerate(zip(POLICIES, axes)):
        for (name, limits), color, style in zip(boundaries.items(), (DENSE, ISOLATED), ("-", "--")):
            low, high = limits[index].T
            ax.fill_between(FOCUS, low, high, where=low <= high, color=color, alpha=0.10)
            ax.plot(FOCUS, low, color=color, lw=1.5, ls=style, label=name)
            ax.plot(FOCUS, high, color=color, lw=1.5, ls=style)
        low, high = common[index]
        ax.fill_between(
            FOCUS, low, high, where=low <= high, interpolate=True,
            color=COMMON, alpha=0.58, label="Common window",
        )
        half_dof = window_metrics(low, high)["centered_dof_at_6_percent_el"] / 2
        ax.add_patch(Rectangle(
            (-half_dof, 1 - BAND_EL), 2 * half_dof, 2 * BAND_EL, fill=False,
            lw=1.5, edgecolor="#151f2e", ls=":", label="6% EL rectangle",
        ))
        ax.plot(0, 1, "o", color="white", markeredgecolor=INK, ms=6.5, zorder=5)
        ax.set(
            xlim=(FOCUS[0], FOCUS[-1]), ylim=(0.89, 1.25), title=policy,
            ylabel="Relative dose D/D₀",
        )
    axes[-1].set_xlabel("Defocus f (λ/NA²)")
    axes[0].legend(loc="upper center", fontsize=11, ncol=2)
    save(fig, "process-window.png")


def main():
    cases = {}
    boundaries = {}
    report = {"features": {}, "comparison": {}}
    mid_focus = np.flatnonzero(np.isclose(FOCUS, 0))[0]
    mid_dose = np.flatnonzero(np.isclose(DOSE, 1))[0]
    for name, pitch in PITCHES.items():
        widths = choose_mask_widths(pitch)
        check_x = np.linspace(0, pitch / 2, 9)
        check_z = np.array([0., 0.32, 0.65])
        integrated = aerial_image(pitch, widths[:1], check_z, check_x)[0]
        reference = source_point_reference(pitch, widths[0], check_z, check_x)
        source_error = float(np.max(np.abs(integrated - reference)))
        assert source_error < 1e-12

        coarse = printed_cd(pitch, widths, 1601)
        cd = printed_cd(pitch, widths, 3201)
        assert np.array_equal(np.isnan(coarse), np.isnan(cd))
        cd_refinement = float(np.nanmax(np.abs(cd - coarse)))
        assert cd_refinement < 1e-5
        limits = acceptance_boundaries(pitch, widths, FOCUS)
        passes = (DOSE >= limits[:, :, :1]) & (DOSE <= limits[:, :, 1:])
        assert np.array_equal(passes, np.abs(cd - TARGET) <= CD_TOL)
        assert np.allclose(limits, limits[:, ::-1, :], atol=1e-12, rtol=0)
        boundaries[name] = limits
        cases[name] = {"widths": widths, "cd": cd}
        report["features"][name] = {
            "pitch": pitch,
            "nominal_cd": dict(zip(POLICIES, cd[:, mid_focus, mid_dose].tolist())),
            "mask_width": dict(zip(POLICIES, widths.tolist())),
            "source_integral_max_error": source_error,
            "max_cd_change_on_refinement": cd_refinement,
        }

    common_lower = np.maximum.reduce([limits[:, :, 0] for limits in boundaries.values()])
    common_upper = np.minimum.reduce([limits[:, :, 1] for limits in boundaries.values()])
    common = list(zip(common_lower, common_upper))
    with (OUTPUT / "focus-exposure-matrix.csv").open("w", newline="") as stream:
        writer = csv.writer(stream, lineterminator="\n")
        writer.writerow(["mask_fit", "focus_lambda_per_na_squared", "dose_over_d0",
                         "dense_cd_lambda_per_na", "isolated_proxy_cd_lambda_per_na",
                         "dense_pass", "isolated_proxy_pass", "common_pass"])
        for index, policy in enumerate(POLICIES):
            for i, f in enumerate(FOCUS):
                for j, d in enumerate(DOSE):
                    cds = [case["cd"][index, i, j] for case in cases.values()]
                    ok = [abs(cd - TARGET) <= CD_TOL for cd in cds]
                    writer.writerow([policy, f"{f:.3f}", f"{d:.3f}",
                                     *[f"{cd:.9f}" if np.isfinite(cd) else "" for cd in cds],
                                     *map(int, ok), int(all(ok))])
            report["comparison"][policy] = window_metrics(*common[index])
            report["comparison"][policy]["individual_fixed_dose_intervals"] = {
                f"{f:.2f}": {
                    name: limits[index, np.flatnonzero(np.isclose(FOCUS, f))[0]].tolist()
                    for name, limits in boundaries.items()
                }
                for f in (0., 0.32, 0.45)
            }
    report["conditions"] = {
        "target_cd": TARGET, "cd_tolerance": CD_TOL, "threshold": THRESHOLD,
        "source_half_width": SIGMA, "trial_width_step": float(WIDTHS[1] - WIDTHS[0]),
        "training_focus_cuts": TRAIN_FOCUS.tolist(),
        "focus_scan": [float(FOCUS[0]), float(FOCUS[-1]), len(FOCUS)],
        "dose_scan": [float(DOSE[0]), float(DOSE[-1]), len(DOSE)],
    }
    (OUTPUT / "results.json").write_text(json.dumps(report, indent=2) + "\n")
    plot_figures(cases, boundaries, common)
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()
