#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Küresel Karbon Bütçesi (GCB 2025), NOAA Mauna Loa Atmosferik CO₂, NCEI Okyanus Isı İçeriği (OHC) ve NSIDC Arktik Deniz Buzu Eşbütünleşme Madenciliği (1958–2026)
Global Carbon Budget (GCB 2025), NOAA Mauna Loa Atmospheric CO₂, NCEI Ocean Heat Content & NSIDC Arctic Sea Ice Cointegration Mining (1958–2026)
==============================================================================
GOMD Python SDK v2.0.0 — Official 100% Real-Data Reproducible Case Study
Google Colab Install: !pip install -q --force-reinstall --no-cache-dir https://gomd.pirireis.edu.tr/sdk/dist/gomd-2.0.0-py3-none-any.whl
"""

# ==============================================================================
# ADIM 0: GOMD Python SDK v2.0.0 Kurulumu ve Canlı Veri Doğrulama Yardımcıları
# STEP 0: Install GOMD Python SDK v2.0.0 & Live GOMD Data Verification Helpers
# ==============================================================================
import importlib
import os
import subprocess
import sys
import math
import json
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

if hasattr(sys.stdout, "reconfigure"):
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass

# Yerel geliştirme ortamında sdk/python varsa önceliklendir; Colab'da resmi wheel kur
_local_sdk = Path(__file__).resolve().parent.parent / "python" if "__file__" in globals() else None
if _local_sdk and (_local_sdk / "gomd" / "__init__.py").is_file():
    if str(_local_sdk) not in sys.path:
        sys.path.insert(0, str(_local_sdk))

_IN_COLAB = "google.colab" in sys.modules
_GOMD_WHEEL_URL = "https://gomd.pirireis.edu.tr/sdk/dist/gomd-2.0.0-py3-none-any.whl"
try:
    import gomd  # noqa: F401
    if _IN_COLAB:
        subprocess.check_call([
            sys.executable, "-m", "pip", "install", "-q",
            "--force-reinstall", "--no-cache-dir", _GOMD_WHEEL_URL
        ])
except ImportError:
    subprocess.check_call([
        sys.executable, "-m", "pip", "install", "-q",
        "--force-reinstall", "--no-cache-dir", _GOMD_WHEEL_URL
    ])

import gomd
for _mod_name in list(sys.modules.keys()):
    if _mod_name == "gomd" or _mod_name.startswith("gomd."):
        importlib.reload(sys.modules[_mod_name])
import gomd
from gomd import GOMDClient

client = GOMDClient("https://gomd.pirireis.edu.tr")


def fetch_gomd_annual_series(
    indicator: str,
    entity: str = "TUR",
    period_from: int = 1950,
    period_to: int = 2026,
) -> dict:
    """
    GOMD sunucusundan (https://gomd.pirireis.edu.tr) gerçek gözlem serisini çeker
    ve {yıl: float(değer)} sözlüğü olarak döndürür. Sentetik veri üretmez.
    """
    rows = client.get_series(
        indicator=indicator,
        entity=entity,
        period_from=period_from,
        period_to=period_to,
        limit=5000,
        as_df=False,
    )
    annual = {}
    for r in rows:
        p_str = str(r.get("period") or "").strip()
        val = r.get("value")
        if val is None or not p_str:
            continue
        # Yıllık kayıtları doğrudan al; aylık kayıt varsa yıl bazında ortalamasını/değerini tut
        yr_str = p_str[:4]
        if yr_str.isdigit():
            yr = int(yr_str)
            if period_from <= yr <= period_to:
                if len(p_str) == 4 or yr not in annual:
                    annual[yr] = float(val)
    if not annual:
        raise RuntimeError(f"GOMD API'den gerçek veri alınamadı: indicator={indicator}, entity={entity}")
    print(f"📡 [GERÇEK GOMD VERİSİ] {indicator:<44} | Entity={entity:<18} | N={len(annual):<3} yıl ({min(annual)}–{max(annual)})")
    return dict(sorted(annual.items()))


print(f"✅ GOMD Python SDK Sürümü / Version : v{gomd.__version__}")
print(f"🌐 Canlı Veri Sunucusu / Server     : {client.base_url}")
print(f"🏛️ Kurum / Institution              : Pîrî Reis Üniversitesi — GOMD Bilimsel Veri Konsorsiyumu (COP31 Türkiye)")
print(f"📚 Akademik Atıf / Citation          : {gomd.cite('apa')[:115]}...")

# ==============================================================================
# ADIM 1: Canlı GOMD Sunucusundan Küresel İklim Referans Serilerinin Çekimi
# STEP 1: Live Retrieval of Global Climate Benchmark Series from GOMD
# ==============================================================================
from gomd.stats import (
    cointegration_eg_test,
    transfer_entropy_causal,
    innovative_polygon_trend,
    mann_kendall_sen,
    pettitt_changepoint,
)

co2_map   = fetch_gomd_annual_series("gml_mauna_loa_co2_ppm", entity="WLD", period_from=1959, period_to=2025)
fos_map   = fetch_gomd_annual_series("gcb2025_fossil", entity="WLD", period_from=1959, period_to=2024)
atm_map   = fetch_gomd_annual_series("gcb2025_atmosphere", entity="WLD", period_from=1959, period_to=2024)
ocn_map   = fetch_gomd_annual_series("gcb2025_ocean_sink", entity="WLD", period_from=1959, period_to=2024)
lnd_map   = fetch_gomd_annual_series("gcb2025_land_sink", entity="WLD", period_from=1959, period_to=2024)
ohc_map   = fetch_gomd_annual_series("ncei_ohc_0_700m", entity="WLD", period_from=1959, period_to=2025)
ice_min_m = fetch_gomd_annual_series("nsidc_arctic_ice_min", entity="ARCTIC", period_from=1979, period_to=2025)
ice_max_m = fetch_gomd_annual_series("nsidc_arctic_ice_max", entity="ARCTIC", period_from=1979, period_to=2025)

gcb_years = sorted(set(co2_map) & set(fos_map) & set(atm_map) & set(ocn_map) & set(lnd_map) & set(ohc_map))
df_gcb = pd.DataFrame([
    {
        "year": y,
        "co2_ppm": round(co2_map[y], 2),
        "fossil_gtc": round(fos_map[y], 3),
        "atmos_gtc": round(atm_map[y], 3),
        "ocean_sink_gtc": round(ocn_map[y], 3),
        "land_sink_gtc": round(lnd_map[y], 3),
        "ocean_sink_fraction_pct": round((ocn_map[y] / max(fos_map[y], 0.1)) * 100.0, 2),
        "ohc_10_22j": round(ohc_map[y], 3),
    }
    for y in gcb_years
])

# 1. Engle & Granger (1987) Eşbütünleşme Testi: Fosil Emisyon -> Okyanus Karbon Yutağı
eg_coint = cointegration_eg_test(df_gcb["fossil_gtc"].tolist(), df_gcb["ocean_sink_gtc"].tolist())

# 2. 1979–2025 Arktik Deniz Buzu ve OHC Nedensellik Analizi
ice_years = sorted(set(ice_min_m) & set(ohc_map) & set(co2_map))
df_ice = pd.DataFrame([
    {
        "year": y,
        "co2_ppm": co2_map[y],
        "ohc_10_22j": ohc_map[y],
        "arctic_ice_min_mkm2": ice_min_m[y],
        "arctic_ice_max_mkm2": ice_max_m.get(y, np.nan),
    }
    for y in ice_years
])

te_ohc_ice = transfer_entropy_causal(
    x=df_ice["ohc_10_22j"].tolist(),
    y=df_ice["arctic_ice_min_mkm2"].tolist(),
    bins=3,
)
mk_ice = mann_kendall_sen(df_ice["arctic_ice_min_mkm2"].tolist(), t=df_ice["year"].tolist())
ipta_co2 = innovative_polygon_trend(df_gcb["co2_ppm"].tolist())

print("\n🌍 Küresel Karbon Bütçesi (GCB 2025) & Mauna Loa CO₂ Özeti (Son 8 Yıl):")
print(df_gcb.tail(8).to_string(index=False))
print(f"\n🔗 Engle-Granger Eşbütünleşme (Fosil -> Okyanus Yutağı) : β = {eg_coint['long_run_slope_beta']:.4f}, ADF t = {eg_coint['engle_granger_adf_t_stat']:.3f} (Kritik %5 = {eg_coint['critical_value_5pct']}, Eşbütünleşik = {eg_coint['cointegrated_at_5pct']})")
print(f"🧊 NSIDC Arktik Eylül Deniz Buzu Trendi                 : {mk_ice['theil_sen_slope']*10:.3f} Milyon km² / 10-yıl (p = {mk_ice['p_value']:.2e})")
print(f"⚡ Shannon Transfer Entropisi T(OHC -> Arktik Buz)      : {te_ohc_ice['transfer_entropy_x_to_y_bits']:.4f} bits ({te_ohc_ice['dominant_causal_direction']})")
print(f"📐 Şen (2020) IPTA Mauna Loa CO₂ Eğimi                   : +{ipta_co2['ita_slope_per_step']:.3f} ppm/yıl (Birinci Yarı = {ipta_co2['first_half_mean']:.2f} -> İkinci Yarı = {ipta_co2['second_half_mean']:.2f} ppm, Kuyruk Çarpanı = {ipta_co2['tail_amplification_ratio']}x)")

# ==============================================================================
# ADIM 2: Küresel Karbon Yutakları ve OHC vs Arktik Deniz Buzu Görselleştirmesi
# STEP 2: Visualization of Global Carbon Sinks & OHC vs. Arctic Sea Ice
# ==============================================================================
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13.5, 5.0), dpi=120)
fig.patch.set_facecolor("#071324")
for ax in (ax1, ax2):
    ax.set_facecolor("#0b1d36")
    ax.tick_params(colors="#cbd5e1")
    for s in ax.spines.values():
        s.set_color("#1e3a5f")

# Panel A: Global Carbon Budget 1959–2024 Gerçek GOMD Serileri (GtC/yıl)
ax1.plot(df_gcb["year"], df_gcb["fossil_gtc"], color="#f43f5e", lw=2.3, label="Fosil CO₂ Emisyonları (GtC/yıl)")
ax1.plot(df_gcb["year"], df_gcb["ocean_sink_gtc"], color="#38bdf8", lw=2.2, label="Okyanus Karbon Yutağı (GtC/yıl)")
ax1.plot(df_gcb["year"], df_gcb["land_sink_gtc"], color="#22c55e", lw=1.9, ls="--", label="Karasal Biyosfer Yutağı (GtC/yıl)")
ax1.set_title("A) Küresel Karbon Bütçesi (GCB 1959–2024 Gerçek GOMD Verisi)", color="#f8fafc", fontweight="bold")
ax1.set_ylabel("Karbon Akısı (GtC / yıl)", color="#cbd5e1")
ax1.legend(facecolor="#0f172a", edgecolor="#334155", labelcolor="#f8fafc", fontsize=8.5)
ax1.grid(alpha=0.18, color="#64748b")

# Panel B: NCEI Okyanus Isı İçeriği (0–700m) vs NSIDC Arktik Eylül Deniz Buzu (1979–2025)
ax2.plot(df_ice["year"], df_ice["ohc_10_22j"], color="#f59e0b", marker="o", lw=2.0, label="NCEI OHC 0–700m (10²² J)")
ax2_t = ax2.twinx()
ax2_t.plot(df_ice["year"], df_ice["arctic_ice_min_mkm2"], color="#38bdf8", marker="s", ls="--", lw=2.0, label="NSIDC Arktik Eylül Minimum Buz (Milyon km²)")
ax2_t.tick_params(colors="#7dd3fc")
ax2.set_title("B) Okyanus Isı İçeriği (OHC) ve Arktik Deniz Buzu Erimesi (1979–2025)", color="#f8fafc", fontweight="bold")
ax2.set_ylabel("Okyanus Isı İçeriği (10²² Joule)", color="#f59e0b")
ax2_t.set_ylabel("Arktik Deniz Buzu Alanı (Milyon km²)", color="#38bdf8")
ax2.grid(alpha=0.18, color="#64748b")

fig.suptitle("GOMD Python SDK v2.0.0 — Vaka Çalışması 7: Küresel Karbon Bütçesi, OHC & Arktik Buz Eşbütünleşmesi", color="#ffffff", fontsize=12.5, fontweight="bold", y=1.01)
plt.tight_layout()
fig.savefig("cs07_global_carbon_budget_mauna_loa_ocean_sink_cointegration.png", dpi=140, bbox_inches="tight", facecolor=fig.get_facecolor())
plt.show()
