"""Generate a synthetic Ti 2p XPS spectrum with TiO2 and Ti2O3 components."""

import numpy as np

np.random.seed(42)

# Binding energy axis (typical Ti 2p range, high-to-low as in XPS convention)
be = np.linspace(470, 452, 500)


def voigt_approx(x, center, sigma, gamma, amplitude):
    """Pseudo-Voigt approximation."""
    fg = 2 * sigma * np.sqrt(2 * np.log(2))
    fl = 2 * gamma
    f = (fg**5 + 2.69269 * fg**4 * fl + 2.42843 * fg**3 * fl**2
         + 4.47163 * fg**2 * fl**3 + 0.07842 * fg * fl**4 + fl**5) ** 0.2
    eta = 1.36603 * (fl / f) - 0.47719 * (fl / f)**2 + 0.11116 * (fl / f)**3
    gauss = np.exp(-4 * np.log(2) * ((x - center) / f)**2) / (f * np.sqrt(np.pi / (4 * np.log(2))))
    lorentz = (f / (2 * np.pi)) / ((x - center)**2 + (f / 2)**2)
    return amplitude * (eta * lorentz + (1 - eta) * gauss)


# --- TiO2 (Ti4+) dominant component ---
# 2p3/2 at 458.8 eV, splitting 5.7 eV, area ratio 2:1
tio2_3_2 = voigt_approx(be, center=458.8, sigma=0.55, gamma=0.3, amplitude=9000)
tio2_1_2 = voigt_approx(be, center=458.8 + 5.7, sigma=0.55, gamma=0.3, amplitude=4500)

# --- Ti2O3 (Ti3+) minor component ---
# 2p3/2 at 457.0 eV, splitting 5.5 eV
ti2o3_3_2 = voigt_approx(be, center=457.0, sigma=0.6, gamma=0.35, amplitude=2500)
ti2o3_1_2 = voigt_approx(be, center=457.0 + 5.5, sigma=0.6, gamma=0.35, amplitude=1250)

# --- Shirley-like background (step function rising toward lower BE) ---
signal = tio2_3_2 + tio2_1_2 + ti2o3_3_2 + ti2o3_1_2
cumul = np.cumsum(signal[::-1])[::-1]
background = 200 + 150 * cumul / cumul.max()

# --- Compose and add noise ---
intensity = signal + background
noise = np.random.normal(0, 15, size=len(be))
intensity += noise
intensity = np.maximum(intensity, 0)

# Save
data = np.column_stack([be, intensity])
np.savetxt(
    "examples/data/xps_ti2p.csv",
    data,
    delimiter=",",
    header="BindingEnergy_eV,Intensity_CPS",
    comments="",
    fmt="%.6e",
)
print(f"Saved xps_ti2p.csv: {len(be)} points, BE range {be.min():.1f}-{be.max():.1f} eV")
