"""
PV degradation uncertainty and lifetime
=======================================

Recalculate four lifetime curves from published coefficients, inspect climate
input differences, and run explicit sensitivity scenarios from Kaaya et al.
(2021), DOI 10.1016/j.solener.2021.01.071. This example runs offline from the
packaged numerical tables; the original field time series are unavailable.

The :doc:`guide </_generated/guides/degradation-uncertainty>` explains the
printed thermal equation, incomplete calibration constants, units, and source
table inconsistencies. Scenario results are not reproductions of paper figures.
"""

import matplotlib.pyplot as plt
import numpy as np

from energy_analysis.degradation_uncertainty.study import (
    climate_input_comparisons,
    climate_sensitivity,
    physical_model_scenario,
    published_tables,
    reliability_table_check,
    synthetic_weather_benchmark,
)
from energy_methods.pv_reliability import ReliabilityCurve

# %%
# Published coefficients: four different extrapolations
# -----------------------------------------------------
# No refit or reconstruction of original observations is claimed. The stretched
# exponential coefficient is in year**(-beta), not a common percent/year rate.
# The threshold is 80% retained power, not a survival probability.

print(reliability_table_check().to_string(index=False))
age = np.linspace(0, 50, 501)
fig, ax = plt.subplots(figsize=(8.5, 5), layout="constrained")
for row in published_tables()["reliability_table3"]:
    curve = ReliabilityCurve(**{k: v for k, v in row.items() if k != "reported_failure_years"})
    ax.plot(age, curve.power(age), label=curve.kind.replace("_", " "))
ax.axhline(0.8, color="black", linestyle="--", label="80% retained power")
ax.axvspan(0, 8.1, alpha=0.08, color="black", label="Paper's observation duration")
ax.set(
    xlabel="Age (years)",
    ylabel="Normalized power",
    ylim=(0, 1.02),
    title="Published Table 3 coefficients: model-dependent extrapolation",
)
ax.legend(fontsize=9)
plt.show()

# %%
# Recompute input differences without inventing hourly records
# ------------------------------------------------------------
# Eq. 20 normalizes by the larger absolute value. Negev's UV reference differs
# between Tables 6 and 10; each comparison preserves its source table. Published
# rounded differences are not used to overwrite the equation's calculated value.

inputs = climate_input_comparisons()
uv = inputs[inputs.variable == "uv_kwh_m2"]
fig, ax = plt.subplots(figsize=(8.5, 4.5), layout="constrained")
uv.pivot(index="site", columns="model", values="relative_difference_percent").plot.barh(ax=ax)
ax.set(
    xlabel="Symmetric relative difference (%)",
    ylabel="",
    title="UV input differences recalculated from Table 10",
)
ax.legend(title="UV model", fontsize=9)
plt.show()

# %%
# Propagate climate substitutions under declared assumptions
# -----------------------------------------------------------
# Table 5 omits normalization and cycling frequency. This explicit scenario
# chooses A_N=1, 365 cycles/year and numerical percent/year conversion. It retains
# the printed 273+delta-T term. It is not a field-validated lifetime prediction.

scenario = climate_sensitivity(
    normalization=1.0, cycles_per_year=365.0, rate_scale_to_year_inverse=0.01
)
temperature = scenario[scenario.driver == "temperature"]
fig, ax = plt.subplots(figsize=(8.5, 5), layout="constrained")
temperature.pivot(
    index="site", columns="model", values="rate_relative_difference_percent"
).plot.barh(ax=ax)
ax.set(
    xlabel="Symmetric rate difference (%)",
    ylabel="",
    title="Temperature sensitivity: UNVALIDATED parameter scenario",
)
plt.show()
print(scenario.to_string(index=False))

# %%
# Synthetic checks of weather calibration and physical models
# -------------------------------------------------------------
# Fit temperature using synthetic 2023 data and evaluate on synthetic 2024 data.
# Targets are generated by Faiman/Wald/Buck, so their advantage is by construction.
# The daily stress-product equation uses daytime irradiance, whereas the combined
# model uses integrated annual UV dose. Assumed scales prevent a fair ranking.

print(synthetic_weather_benchmark().to_string(index=False))
print(physical_model_scenario().to_string(index=False))
