#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Doğal Sermaye, İklim Kaynaklı Kayıplar ve Deniz Koruma: Dünya Bankası CWON, Eurostat/EEA Ekonomik Kayıplar, OECD Deniz Koruma Alanları ve Sigorta Hizmetleri
Natural Capital, Climate-Related Losses & Marine Protection: World Bank CWON, Eurostat/EEA Economic Losses, OECD Marine Protected Areas & Insurance Services
==============================================================================
GOMD Python SDK — Gerçek veriyle yeniden üretilebilir vaka çalışması / Reproducible real-data case study
Google Colab Install: !pip install -q --upgrade gomd

Veri kaynakları / Data sources (hepsi GOMD sunucusundan canlı çekilir / all fetched live from the GOMD server):
  - wb_gdp_current, wb_cwon_* — Dünya Bankası düzeltilmiş net tasarruf ve doğal kaynak tükenmesi (CWON)
  - eurostat_climate_economic_losses_eur_hab — Eurostat/EEA iklim kaynaklı ekonomik kayıplar, kişi başına (sdg_13_40)
  - OECD_SOE_MARINE_PT_EEZ_ALL_INC_P_NA, OECD_SOE_MARINE_KM2_ALL_INC_P_NA — OECD deniz koruma alanları
  - wb_insurance_financial_services_exports_pct / _imports_pct — Dünya Bankası BX/BM.GSR.INSF.ZS

Not / Note: Bu betik sentetik veri üretmez. Bir seri sunucuda yoksa betik açık bir hata mesajıyla durur.
            This script never generates synthetic data. If a series is missing on the server, it stops with an explicit error.
"""

# ==============================================================================
# ADIM 0: GOMD Python SDK Kurulumu ve Canlı Veri Yardımcıları
# STEP 0: Install the GOMD Python SDK & Live Data 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

_IN_COLAB = "google.colab" in sys.modules
_GOMD_WHEEL_URL = "https://gomd.pirireis.edu.tr/sdk/dist/gomd-2.0.1-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_records(indicator: str, entity: str, period_from=None, period_to=None, limit: int = 50000) -> pd.DataFrame:
    """
    GOMD sunucusundan bir göstergenin TEK bir varlık (ülke/havza) için ham kayıtlarını çeker.
    Yalnız istenen varlığın kayıtları tutulur; sunucu başka bir varlık döndürürse kullanılmaz.
    Returns a DataFrame with columns: period (str), value (float).
    """
    rows = client.get_series(indicator=indicator, entity=entity, period_from=period_from,
                             period_to=period_to, limit=limit, as_df=False)
    keep = [r for r in rows if str(r.get("entity_code") or "") == entity and r.get("value") is not None]
    if not keep:
        raise RuntimeError(f"GOMD sunucusunda veri yok: indicator={indicator}, entity={entity}")
    df = pd.DataFrame({"period": [str(r["period"]) for r in keep], "value": [float(r["value"]) for r in keep]})
    df = df.drop_duplicates("period").sort_values("period").reset_index(drop=True)
    print(f"📡 [GOMD] {indicator:<44} | {entity:<18} | N={len(df):<6} ({df['period'].iloc[0][:10]} – {df['period'].iloc[-1][:10]})")
    return df


def fetch_gomd_annual_series(indicator: str, entity: str, period_from: int = 1900, period_to: int = 2100,
                             how: str = "mean", min_count: int = 1) -> dict:
    """
    Yıllık seri döndürür: {yıl: değer}. Kayıtlar yıllık değilse (aylık/günlük) yıl içi ortalama alınır
    ve yalnız en az `min_count` kaydı olan yıllar tutulur. Returns {year: value}.
    """
    df = fetch_gomd_records(indicator, entity)
    df["year"] = df["period"].str[:4].astype(int)
    df = df[(df["year"] >= period_from) & (df["year"] <= period_to)]
    g = df.groupby("year")["value"]
    agg = g.mean() if how == "mean" else g.last()
    cnt = g.count()
    out = {int(y): float(v) for y, v in agg.items() if cnt[y] >= min_count}
    if not out:
        raise RuntimeError(f"Seçilen dönemde veri yok: indicator={indicator}, entity={entity}")
    return dict(sorted(out.items()))


def fmt_p(p: float) -> str:
    """p değerini okunur biçimde yazar / readable p-value."""
    return "<1e-6" if p < 1e-6 else f"{p:.4f}"


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 & T.C. Çevre, Şehircilik ve İklim Değişikliği Bakanlığı Çevre Yönetimi Genel Müdürlüğü — GOMD (COP31 Türkiye)")

# ==============================================================================
# ADIM 1: Dünya Bankası CWON — Türkiye'nin Düzeltilmiş Net Tasarrufu ve Doğal Sermaye Tükenmesi
# STEP 1: World Bank CWON — Türkiye adjusted net savings & natural capital depletion
# ==============================================================================
from gomd.stats import mann_kendall_sen, pettitt_changepoint
from gomd.maritime import kunming_montreal_30x30_gap

gdp = fetch_gomd_annual_series("wb_gdp_current", "TUR")
cwon = {
    "Düzeltilmiş net tasarruf": fetch_gomd_annual_series("wb_cwon_adjusted_net_savings_usd", "TUR"),
    "CO₂ hasar maliyeti": fetch_gomd_annual_series("wb_cwon_carbon_dioxide_damage_usd", "TUR"),
    "Enerji tükenmesi": fetch_gomd_annual_series("wb_cwon_energy_depletion_usd", "TUR"),
    "Mineral tükenmesi": fetch_gomd_annual_series("wb_cwon_mineral_depletion_usd", "TUR"),
    "Net orman tükenmesi": fetch_gomd_annual_series("wb_cwon_net_forest_depletion_usd", "TUR"),
}
cwon_pct = {k: {y: 100 * v[y] / gdp[y] for y in v if y in gdp and gdp[y]} for k, v in cwon.items()}
last = max(cwon_pct["Düzeltilmiş net tasarruf"])
print(f"\n💰 Türkiye CWON bileşenleri, GSYH'ye oran (%), {last}:")
for k, v in cwon_pct.items():
    yy = max(v); print(f"   {k:<28}: %{v[yy]:6.2f}  ({yy})")
ans = cwon_pct["Düzeltilmiş net tasarruf"]
mk_ans = mann_kendall_sen(list(ans.values()), t=list(ans))
print(f"📈 Düzeltilmiş net tasarruf / GSYH trendi: {mk_ans['theil_sen_slope']:+.3f} puan/yıl (p = {fmt_p(mk_ans['p_value'])})")

# ==============================================================================
# ADIM 2: İklim Kaynaklı Ekonomik Kayıplar (Eurostat/EEA, sabit fiyatlar) — Akdeniz ülkeleri
# STEP 2: Climate-related economic losses (Eurostat/EEA, constant prices) — Mediterranean peers
# ==============================================================================
med = ["TUR", "GRC", "ITA", "ESP", "FRA"]
loss = {iso: fetch_gomd_annual_series("eurostat_climate_economic_losses_eur_hab", iso) for iso in med}
loss_rows = []
for iso in med:
    s = loss[iso]; yy = sorted(s)
    mk = mann_kendall_sen([s[y] for y in yy], t=yy)
    early = np.mean([s[y] for y in yy if 1980 <= y <= 1999]); late = np.mean([s[y] for y in yy if y >= 2005])
    loss_rows.append({"ISO": iso, "Dönem": f"{yy[0]}–{yy[-1]}", "1980–99 ort. (€/kişi)": round(early, 1),
                      "2005+ ort. (€/kişi)": round(late, 1), "Sen eğimi (€/kişi/yıl)": round(mk["theil_sen_slope"], 2),
                      "p": fmt_p(mk["p_value"])})
df_loss = pd.DataFrame(loss_rows)
print("\n🌪️ İklim kaynaklı ekonomik kayıplar, kişi başına (sabit fiyat, Eurostat sdg_13_40):")
print(df_loss.to_string(index=False))

# ==============================================================================
# ADIM 3: Deniz Koruma Alanları (OECD, MEB'in %'si) ve 30x30 Hedefi Açığı
# STEP 3: Marine protected areas (OECD, % of EEZ) & the 30x30 gap
# ==============================================================================
mpa_pct = {iso: fetch_gomd_annual_series("OECD_SOE_MARINE_PT_EEZ_ALL_INC_P_NA", iso) for iso in med}
mpa_km2 = {iso: fetch_gomd_annual_series("OECD_SOE_MARINE_KM2_ALL_INC_P_NA", iso) for iso in med}
gap_rows = []
for iso in med:
    y = max(set(mpa_pct[iso]) & set(mpa_km2[iso]))
    pct, km2 = mpa_pct[iso][y], mpa_km2[iso][y]
    eez = km2 / (pct / 100) if pct > 0 else float("nan")   # MEB alanı, iki gerçek seriden türetilir
    g = kunming_montreal_30x30_gap(current_mpa_pct=pct, eez_area_km2=eez, current_year=y) if pct > 0 else None
    gap_rows.append({"ISO": iso, "Yıl": y, "DKA (% MEB)": round(pct, 2), "DKA (km²)": round(km2),
                     "Türetilmiş MEB (km²)": round(eez) if pct > 0 else None,
                     "30x30 için ek alan (km²)": round(g["additional_area_needed_km2"]) if g else None})
df_gap = pd.DataFrame(gap_rows)
print("\n🐟 Deniz koruma alanları ve Kunming-Montreal 30x30 açığı (OECD):")
print(df_gap.to_string(index=False))

# ==============================================================================
# ADIM 4: Sigorta ve Finansal Hizmetler — hizmet ihracatı/ithalatı içindeki pay, ödemeler dengesi (Dünya Bankası BX/BM.GSR.INSF.ZS)
# STEP 4: Insurance & financial services, share of service exports/imports, BoP (World Bank BX/BM.GSR.INSF.ZS)
# ==============================================================================
ins_x = {iso: fetch_gomd_annual_series("wb_insurance_financial_services_exports_pct", iso) for iso in ("TUR", "GRC", "ITA")}
ins_m = {iso: fetch_gomd_annual_series("wb_insurance_financial_services_imports_pct", iso) for iso in ("TUR", "GRC", "ITA")}
print("ℹ️  Not: BX/BM.GSR.INSF.ZS tüm sigorta ve finansal hizmetleri kapsar; yalnız deniz sigortası değildir.")

# ==============================================================================
# ADIM 5: 4 Panelli Görselleştirme / 4-panel figure
# ==============================================================================
fig, axes = plt.subplots(2, 2, figsize=(14, 9.5), dpi=120)
fig.patch.set_facecolor("#071324")
for ax in axes.flat:
    ax.set_facecolor("#0b1d36"); ax.tick_params(colors="#cbd5e1")
    for sp in ax.spines.values():
        sp.set_color("#1e3a5f")
    ax.grid(alpha=0.18, color="#64748b")
leg = dict(facecolor="#0f172a", edgecolor="#334155", labelcolor="#f8fafc", fontsize=8)
pal = {"TUR": "#f43f5e", "GRC": "#38bdf8", "ITA": "#22c55e", "ESP": "#f59e0b", "FRA": "#a78bfa"}

ax1 = axes[0, 0]
for (k, v), c in zip(cwon_pct.items(), ["#38bdf8", "#f43f5e", "#f59e0b", "#a78bfa", "#22c55e"]):
    yy = sorted(v); ax1.plot(yy, [v[y] for y in yy], color=c, lw=1.8, label=k)
ax1.axhline(0, color="#94a3b8", lw=0.8)
ax1.set_ylabel("% GSYH", color="#cbd5e1")
ax1.set_title("A) Türkiye: CWON doğal sermaye hesapları (% GSYH)", color="#f8fafc", fontweight="bold"); ax1.legend(**leg)

ax2 = axes[0, 1]
for iso in med:
    s = pd.Series(loss[iso]).sort_index().rolling(5, min_periods=3).mean()
    ax2.plot(s.index, s.values, color=pal[iso], lw=2, label=iso)
ax2.set_ylabel("€ / kişi (sabit fiyat, 5 yıllık hareketli ort.)", color="#cbd5e1")
ax2.set_title("B) İklim kaynaklı ekonomik kayıplar (Eurostat/EEA)", color="#f8fafc", fontweight="bold"); ax2.legend(**leg)

ax3 = axes[1, 0]
for iso in med:
    s = mpa_pct[iso]; yy = sorted(s); ax3.plot(yy, [s[y] for y in yy], color=pal[iso], lw=2, marker="o", ms=3, label=iso)
ax3.axhline(30, color="#e2e8f0", ls="--", lw=1.2, label="Kunming-Montreal hedefi (%30, 2030)")
ax3.set_yscale("symlog", linthresh=1)
ax3.set_ylabel("% MEB", color="#cbd5e1")
ax3.set_title("C) Deniz koruma alanı, MEB'in yüzdesi (OECD)", color="#f8fafc", fontweight="bold"); ax3.legend(**leg)

ax4 = axes[1, 1]
for iso in ("TUR", "GRC", "ITA"):
    s = ins_x[iso]; yy = sorted(s); ax4.plot(yy, [s[y] for y in yy], color=pal[iso], lw=1.8, label=f"{iso} ihracat")
    s = ins_m[iso]; yy = sorted(s); ax4.plot(yy, [s[y] for y in yy], color=pal[iso], lw=1.2, ls="--", label=f"{iso} ithalat")
ax4.set_ylabel("% hizmet ihracatı / ithalatı (BoP)", color="#cbd5e1")
ax4.set_title("D) Sigorta ve finansal hizmetler payı (Dünya Bankası)", color="#f8fafc", fontweight="bold"); ax4.legend(ncol=2, **leg)

fig.suptitle("GOMD — Vaka Çalışması 3: Doğal sermaye, iklim kayıpları, deniz koruma ve sigorta hizmetleri (gerçek veri)", color="#ffffff", fontsize=12.5, fontweight="bold")
plt.tight_layout()
fig.savefig("cs03_blue_finance_actuarial_insurance_cwon.png", dpi=140, bbox_inches="tight", facecolor=fig.get_facecolor())
plt.show()
