"""Additional file 4.

Reproduces the indirect products (ab) and their approximate 95% confidence
intervals for the exploratory PRI model (walking) from the 50-site SmartPLS
path estimates and bootstrap standard errors reported in Additional file 3.

Two intervals are computed:
  * delta-method (first-order Sobel) interval;
  * Monte Carlo interval (Preacher & Selig 2012), which respects the skewed
    sampling distribution of a product of coefficients.
Both assume zero covariance between the a and b estimates. The preferred
interval is the percentile bootstrap of the specific indirect effect reported
directly by SmartPLS, which does not need this assumption.

Usage:  python Supplementary_Code_1_delta_indirect_ci.py
Requires Python >= 3.8 and NumPy.
"""

from math import sqrt

import numpy as np

N_DRAWS = 1_000_000
SEED = 2026


def delta_interval(a, se_a, b, se_b):
    product = a * b
    se_product = sqrt((b * se_a) ** 2 + (a * se_b) ** 2)
    return product, product - 1.96 * se_product, product + 1.96 * se_product


def monte_carlo_interval(a, se_a, b, se_b, n=N_DRAWS, seed=SEED):
    rng = np.random.default_rng(seed)
    draws = rng.normal(a, se_a, n) * rng.normal(b, se_b, n)
    lower, upper = np.percentile(draws, [2.5, 97.5])
    return float(lower), float(upper)


# (a, SE_a, b, SE_b, direct-model total path c for walking)
paths = {
    "Internal spatial characteristics -> PRI -> walking": (0.264, 0.107, 0.382, 0.113, 0.437),
    "Surrounding urban context -> PRI -> walking": (0.332, 0.121, 0.382, 0.113, 0.258),
}

for label, (a, se_a, b, se_b, c_total) in paths.items():
    product, d_lo, d_hi = delta_interval(a, se_a, b, se_b)
    mc_lo, mc_hi = monte_carlo_interval(a, se_a, b, se_b)
    share = product / c_total
    print(f"{label}: ab = {product:.6f}; share of direct-model path c = {share:.1%}")
    print(f"    delta-method 95% CI: {d_lo:.6f} to {d_hi:.6f}")
    print(f"    Monte Carlo 95% CI:  {mc_lo:.6f} to {mc_hi:.6f}")
