"""
Additional file 1

Format: Python source code (.py)
Title: Reproducible scenario and sensitivity analysis
Description: Executable code for the conditional revenue equations,
deterministic break-even grid, stratified Latin hypercube sampling,
fixed-carbon-price analysis, summary statistics, Spearman rank correlations,
and reproduction of Figures 4 and 5.

The script corresponds to the manuscript submitted to Carbon Balance and
Management. It does not require the third-party operational inventory because
the scenario analysis uses the aggregate area and logging intensity reported
in the manuscript.

Software environment reported in the manuscript:
    Python 3.12.14
    NumPy 2.3.5
    pandas 2.2.3

Additional plotting dependency:
    Pillow

Run:
    python Additional_file_1.py

Outputs are written to the folder ``additional_file_1_outputs``:
    - figure_4.png
    - figure_5.png
    - lhs_results.csv
    - summary_statistics.csv
    - spearman_correlations.csv
    - fixed_price_sensitivity.csv
"""

from pathlib import Path

import numpy as np
import pandas as pd
from PIL import Image, ImageDraw, ImageFont


# ---------------------------------------------------------------------------
# Reproducibility settings and parameters reported in the manuscript
# ---------------------------------------------------------------------------

SEED = 20260804
N_COMBINATIONS = 100_000

# Fixed parameters
A = 27_454.7336459  # reconstructed annual area (ha)
I = 21.30  # mean post-harvest logging intensity (m3 ha-1)
CF = 0.47  # carbon fraction

# Central/reference values
PC_REFERENCE = 7.87  # carbon price (US$ tCO2e-1)
PT_CENTRAL = 50.00  # licensed standing-timber price (US$ m-3)
WD_CENTRAL = 0.62  # basic wood density (Mg m-3)
DF_CENTRAL = 0.20  # collateral damage factor

# Ranges used in the stratified Latin hypercube sampling
RANGES = {
    "Pc": (5.00, 50.00),
    "q": (0.25, 1.00),
    "s": (0.10, 0.30),
    "DF": (0.00, 0.50),
    "WD": (0.62, 0.73),
    "Pt": (30.00, 70.00),
}

OUTPUT_DIR = Path(__file__).resolve().parent / "additional_file_1_outputs"
OUTPUT_DIR.mkdir(exist_ok=True)


# ---------------------------------------------------------------------------
# Model equations
# ---------------------------------------------------------------------------

def calculate_outputs(Pc, q, s, DF, WD, Pt):
    """Calculate the quantities and conditional revenues used in the study."""
    Qbio = A * I * WD * CF * (1.0 + DF) * (44.0 / 12.0)
    Rcarbon_own = q * Pc * Qbio
    Rlease = s * Pt * A * I
    delta_R = Rcarbon_own - Rlease
    Pc_star = (s * Pt) / (q * WD * CF * (1.0 + DF) * (44.0 / 12.0))
    CR = Rcarbon_own / Rlease
    return Qbio, Rcarbon_own, Rlease, delta_R, Pc_star, CR


def stratified_latin_hypercube(n, ranges, seed):
    """Draw one value from every marginal stratum and permute each input."""
    rng = np.random.default_rng(seed)
    sample = {}
    for name, (lower, upper) in ranges.items():
        unit_values = (np.arange(n) + rng.random(n)) / n
        rng.shuffle(unit_values)
        sample[name] = lower + (upper - lower) * unit_values
    return pd.DataFrame(sample)


def spearman_correlations(frame, response):
    """Calculate Spearman correlations as Pearson correlations of ranks."""
    ranked_response = pd.Series(response).rank(method="average").to_numpy()
    correlations = {}
    for column in RANGES:
        ranked_input = frame[column].rank(method="average").to_numpy()
        correlations[column] = np.corrcoef(ranked_input, ranked_response)[0, 1]
    return pd.Series(correlations, name="spearman_rho")


# ---------------------------------------------------------------------------
# Figure 4: deterministic grid and analytical break-even frontier
# ---------------------------------------------------------------------------

def _font(size, bold=False):
    candidates = [
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
        "/Library/Fonts/Arial Bold.ttf" if bold else "/Library/Fonts/Arial.ttf",
    ]
    for path in candidates:
        try:
            return ImageFont.truetype(path, size)
        except OSError:
            pass
    return ImageFont.load_default()


def _map_x(value, lower, upper, left, right):
    return left + (value - lower) * (right - left) / (upper - lower)


def _map_y(value, lower, upper, top, bottom):
    return bottom - (value - lower) * (bottom - top) / (upper - lower)


def _vertical_label(image, text, center, font):
    """Draw a centered vertical label without clipping the page margin."""
    box = font.getbbox(text)
    layer = Image.new("RGBA", (box[2] - box[0] + 20, box[3] - box[1] + 20), (255, 255, 255, 0))
    ImageDraw.Draw(layer).text((10, 10), text, fill="black", font=font, anchor="la")
    layer = layer.rotate(90, expand=True)
    image.paste(layer, (int(center[0] - layer.width / 2), int(center[1] - layer.height / 2)), layer)


def create_figure_4():
    pc_values = np.linspace(5.0, 50.0, 181)
    s_values = np.linspace(0.05, 0.30, 151)
    pc_grid, s_grid = np.meshgrid(pc_values, s_values)
    q_values = (0.25, 0.50, 0.75)

    canvas = Image.new("RGB", (3000, 980), "white")
    draw = ImageDraw.Draw(canvas)
    title_font = _font(42, bold=True)
    label_font = _font(27)
    tick_font = _font(23)
    draw.text((1500, 45), "Conditional frontier between forest protection and timber leasing", fill="black", font=title_font, anchor="mm")
    for panel, q_value in enumerate(q_values):
        left = 150 + panel * 960
        right = left + 790
        top, bottom = 150, 790
        _, _, _, delta_R, _, _ = calculate_outputs(
            pc_grid,
            q_value,
            s_grid,
            DF_CENTRAL,
            WD_CENTRAL,
            PT_CENTRAL,
        )
        # Rasterize each grid cell: blue = leasing, red = protection.
        for yi in range(len(s_values) - 1):
            y0 = int(_map_y(s_values[yi], 0.05, 0.30, top, bottom))
            y1 = int(_map_y(s_values[yi + 1], 0.05, 0.30, top, bottom))
            for xi in range(len(pc_values) - 1):
                x0 = int(_map_x(pc_values[xi], 5, 50, left, right))
                x1 = int(_map_x(pc_values[xi + 1], 5, 50, left, right))
                color = "#d73027" if delta_R[yi, xi] > 0 else "#4575b4"
                draw.rectangle((x0, y1, x1 + 1, y0 + 1), fill=color)
        # Analytical frontier s* = q*Pc*WD*CF*(1+DF)*(44/12)/Pt.
        frontier = q_value * pc_values * WD_CENTRAL * CF * (1 + DF_CENTRAL) * (44 / 12) / PT_CENTRAL
        points = [
            (_map_x(pc, 5, 50, left, right), _map_y(sv, 0.05, 0.30, top, bottom))
            for pc, sv in zip(pc_values, frontier)
            if 0.05 <= sv <= 0.30
        ]
        if len(points) > 1:
            draw.line(points, fill="black", width=6)
        ref_x = _map_x(PC_REFERENCE, 5, 50, left, right)
        for y in range(top, bottom, 24):
            draw.line((ref_x, y, ref_x, min(y + 12, bottom)), fill="white", width=4)
        draw.rectangle((left, top, right, bottom), outline="black", width=4)
        for tick in (5, 10, 20, 30, 40, 50):
            x = _map_x(tick, 5, 50, left, right)
            draw.line((x, bottom, x, bottom + 10), fill="black", width=3)
            draw.text((x, bottom + 18), str(tick), fill="black", font=tick_font, anchor="ma")
        for tick in (0.05, 0.10, 0.15, 0.20, 0.25, 0.30):
            y = _map_y(tick, 0.05, 0.30, top, bottom)
            draw.line((left - 10, y, left, y), fill="black", width=3)
            draw.text((left - 18, y), f"{tick:.2f}", fill="black", font=tick_font, anchor="rm")
        draw.text(((left + right) / 2, 115), f"q = {q_value:.2f}", fill="black", font=label_font, anchor="mm")
        draw.text(((left + right) / 2, 885), "Carbon price, Pc (US$ tCO2e-1)", fill="black", font=label_font, anchor="mm")
        if panel == 0:
            _vertical_label(canvas, "Landowner share of timber revenue, s", (35, (top + bottom) / 2), label_font)
    canvas.save(OUTPUT_DIR / "figure_4.png", dpi=(300, 300))


# ---------------------------------------------------------------------------
# Figure 5: Latin hypercube sensitivity analysis
# ---------------------------------------------------------------------------

def create_figure_5(results, fixed_price_curve, correlations):
    canvas = Image.new("RGB", (3000, 1700), "white")
    draw = ImageDraw.Draw(canvas)
    title_font = _font(34, bold=True)
    label_font = _font(26)
    tick_font = _font(22)

    # A: histogram in 50 classes.
    a_left, a_right, a_top, a_bottom = 160, 1420, 150, 760
    counts, edges = np.histogram(results["delta_R"] / 1_000_000, bins=50)
    max_count = counts.max()
    for count, x0v, x1v in zip(counts, edges[:-1], edges[1:]):
        x0 = _map_x(x0v, edges[0], edges[-1], a_left, a_right)
        x1 = _map_x(x1v, edges[0], edges[-1], a_left, a_right)
        y = _map_y(count, 0, max_count, a_top, a_bottom)
        draw.rectangle((x0, y, x1, a_bottom), fill="#4f81bd", outline="white")
    zero_x = _map_x(0, edges[0], edges[-1], a_left, a_right)
    draw.line((zero_x, a_top, zero_x, a_bottom), fill="red", width=5)
    draw.rectangle((a_left, a_top, a_right, a_bottom), outline="black", width=4)
    draw.text((a_left, 90), "A  Distribution of ΔR", fill="black", font=title_font)
    draw.text(((a_left + a_right) / 2, 820), "ΔR (US$ million)", fill="black", font=label_font, anchor="mm")
    _vertical_label(canvas, "Combinations", (55, (a_top + a_bottom) / 2), label_font)

    # B: favorable domain coverage at 91 fixed carbon prices.
    b_left, b_right, b_top, b_bottom = 1650, 2890, 150, 760
    curve_points = [
        (_map_x(pc, 5, 50, b_left, b_right), _map_y(cv, 0, 100, b_top, b_bottom))
        for pc, cv in zip(fixed_price_curve["Pc"], fixed_price_curve["favorable_domain_coverage_percent"])
    ]
    draw.line(curve_points, fill="#2f6fb3", width=7)
    reference_coverage = np.interp(
        PC_REFERENCE,
        fixed_price_curve["Pc"],
        fixed_price_curve["favorable_domain_coverage_percent"],
    )
    rx = _map_x(PC_REFERENCE, 5, 50, b_left, b_right)
    ry = _map_y(reference_coverage, 0, 100, b_top, b_bottom)
    draw.ellipse((rx - 10, ry - 10, rx + 10, ry + 10), fill="red")
    draw.text((rx + 18, ry - 12), f"US$ {PC_REFERENCE:.2f}: {reference_coverage:.1f}%", fill="red", font=tick_font)
    draw.rectangle((b_left, b_top, b_right, b_bottom), outline="black", width=4)
    draw.text((b_left, 90), "B  Fixed-price sensitivity", fill="black", font=title_font)
    draw.text(((b_left + b_right) / 2, 820), "Carbon price, Pc (US$ tCO2e-1)", fill="black", font=label_font, anchor="mm")
    _vertical_label(canvas, "Combinations favoring protection (%)", (1540, (b_top + b_bottom) / 2), label_font)

    # C: Spearman rank correlations.
    order = ["Pc", "q", "DF", "WD", "Pt", "s"]
    values = correlations.loc[order]
    c_left, c_right, c_top, c_bottom = 360, 2700, 1050, 1550
    zero = _map_x(0, -0.25, 0.85, c_left, c_right)
    draw.line((zero, c_top, zero, c_bottom), fill="black", width=4)
    row_h = (c_bottom - c_top) / len(order)
    for i, (name, value) in enumerate(values.items()):
        y0 = c_top + i * row_h + 12
        y1 = c_top + (i + 1) * row_h - 12
        x_value = _map_x(value, -0.25, 0.85, c_left, c_right)
        color = "#4f81bd" if value >= 0 else "#f47c20"
        draw.rectangle((min(zero, x_value), y0, max(zero, x_value), y1), fill=color)
        draw.text((c_left - 35, (y0 + y1) / 2), name, fill="black", font=label_font, anchor="rm")
        draw.text((x_value + (16 if value >= 0 else -16), (y0 + y1) / 2), f"{value:.3f}", fill="black", font=tick_font, anchor="lm" if value >= 0 else "rm")
    draw.text((c_left, 960), "C  Association of inputs with ΔR", fill="black", font=title_font)
    draw.text(((c_left + c_right) / 2, 1640), "Spearman rank correlation with ΔR", fill="black", font=label_font, anchor="mm")
    canvas.save(OUTPUT_DIR / "figure_5.png", dpi=(300, 300))


def main():
    # Latin hypercube sample in the input order reported in the manuscript.
    sampled = stratified_latin_hypercube(N_COMBINATIONS, RANGES, SEED)
    outputs = calculate_outputs(
        sampled["Pc"].to_numpy(),
        sampled["q"].to_numpy(),
        sampled["s"].to_numpy(),
        sampled["DF"].to_numpy(),
        sampled["WD"].to_numpy(),
        sampled["Pt"].to_numpy(),
    )
    output_names = ["Qbio", "Rcarbon_own", "Rlease", "delta_R", "Pc_star", "CR"]
    for name, values in zip(output_names, outputs):
        sampled[name] = values

    # Summary of the full assumption domain.
    summary = pd.DataFrame(
        {
            "metric": [
                "delta_R_median_USD",
                "delta_R_5th_percentile_USD",
                "delta_R_95th_percentile_USD",
                "favorable_domain_coverage_percent",
            ],
            "value": [
                sampled["delta_R"].median(),
                sampled["delta_R"].quantile(0.05),
                sampled["delta_R"].quantile(0.95),
                100.0 * (sampled["delta_R"] > 0).mean(),
            ],
        }
    )

    # Fixed-price analysis retains the same sampled q, s, DF, WD, and Pt.
    fixed_prices = np.linspace(5.0, 50.0, 91)
    fixed_coverage = []
    for price in fixed_prices:
        _, _, _, delta_fixed, _, _ = calculate_outputs(
            price,
            sampled["q"].to_numpy(),
            sampled["s"].to_numpy(),
            sampled["DF"].to_numpy(),
            sampled["WD"].to_numpy(),
            sampled["Pt"].to_numpy(),
        )
        fixed_coverage.append(100.0 * (delta_fixed > 0).mean())
    fixed_price_curve = pd.DataFrame(
        {
            "Pc": fixed_prices,
            "favorable_domain_coverage_percent": fixed_coverage,
        }
    )

    # Exact reference-price result, calculated separately because 7.87 is not
    # one of the 91 equally spaced values from 5 to 50.
    _, _, _, delta_reference, _, _ = calculate_outputs(
        PC_REFERENCE,
        sampled["q"].to_numpy(),
        sampled["s"].to_numpy(),
        sampled["DF"].to_numpy(),
        sampled["WD"].to_numpy(),
        sampled["Pt"].to_numpy(),
    )
    reference_coverage = 100.0 * (delta_reference > 0).mean()

    correlations = spearman_correlations(sampled, sampled["delta_R"])

    sampled.to_csv(OUTPUT_DIR / "lhs_results.csv", index=False)
    summary.to_csv(OUTPUT_DIR / "summary_statistics.csv", index=False)
    correlations.to_csv(OUTPUT_DIR / "spearman_correlations.csv", header=True)
    fixed_price_curve.to_csv(OUTPUT_DIR / "fixed_price_sensitivity.csv", index=False)

    create_figure_4()
    create_figure_5(sampled, fixed_price_curve, correlations)

    print(summary.to_string(index=False))
    print(f"Reference-price favorable domain coverage: {reference_coverage:.1f}%")
    print("Spearman rank correlations:")
    print(correlations.to_string())
    print(f"Outputs written to: {OUTPUT_DIR}")


if __name__ == "__main__":
    main()
