#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
COP31 Türkiye Enerji Dönüşümü, JRC EDGAR Sektörel Sera Gazı Envanteri, IEA Yenilenebilir Enerji ve BIST Denizcilik İklim Geçiş VaR Analizi (1970–2026)
COP31 Energy Transition, JRC EDGAR Sectoral GHG Inventory, IEA Renewable Energy & BIST Maritime Climate Transition VaR Analysis (1970–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 JRC EDGAR Sektörel GHG, IEA ve BIST VaR Serileri
# STEP 1: Live Retrieval of JRC EDGAR Sectoral GHG, IEA Renewables & BIST VaR
# ==============================================================================
from gomd.stats import (
    panel_fixed_effects,
    cointegration_eg_test,
    mann_kendall_sen,
    pettitt_changepoint,
)

panel_countries = ["TUR", "DEU", "FRA", "ITA", "ESP", "GRC"]

# 1. Türkiye (TUR) 1970–2024 JRC EDGAR sektörel emisyonları
tur_ghg_tot  = fetch_gomd_annual_series("edgar_wb_total_ghg_excl_lulucf_mt_co2e", entity="TUR", period_from=1970, period_to=2024)
tur_co2_trn  = fetch_gomd_annual_series("edgar_wb_co2_transport_mt", entity="TUR", period_from=1970, period_to=2024)
tur_co2_pwr  = fetch_gomd_annual_series("edgar_wb_co2_power_industry_mt", entity="TUR", period_from=1970, period_to=2024)
tur_ren_elec = fetch_gomd_annual_series("iea_wb_renewable_electricity_output_pct", entity="TUR", period_from=1990, period_to=2024)
tur_bist_var = fetch_gomd_annual_series("bist_maritime_climate_transition_var_pct", entity="TUR", period_from=1990, period_to=2026)
tur_port_slr = fetch_gomd_annual_series("coastal_port_slr_inundation_exposure_idx", entity="TUR", period_from=1990, period_to=2026)

edgar_years = sorted(set(tur_ghg_tot) & set(tur_co2_trn) & set(tur_co2_pwr))
df_tur_edgar = pd.DataFrame([
    {
        "year": y,
        "total_ghg_mt": round(tur_ghg_tot[y], 2),
        "transport_co2_mt": round(tur_co2_trn[y], 2),
        "power_co2_mt": round(tur_co2_pwr[y], 2),
        "transport_share_pct": round((tur_co2_trn[y] / max(tur_ghg_tot[y], 1.0)) * 100.0, 2),
    }
    for y in edgar_years
])

# 2. 6 Ülkeli (TUR, DEU, FRA, ITA, ESP, GRC) Gerçek GOMD Panel Regresyonu (Fixed Effects Within)
fe_panel_rows = []
country_latest_rows = []

for iso in panel_countries:
    ghg_s = fetch_gomd_annual_series("edgar_wb_total_ghg_excl_lulucf_mt_co2e", entity=iso, period_from=1990, period_to=2024)
    trn_s = fetch_gomd_annual_series("edgar_wb_co2_transport_mt", entity=iso, period_from=1990, period_to=2024)
    pwr_s = fetch_gomd_annual_series("edgar_wb_co2_power_industry_mt", entity=iso, period_from=1990, period_to=2024)
    ren_s = fetch_gomd_annual_series("iea_wb_renewable_energy_final_consumption_pct", entity=iso, period_from=1990, period_to=2024)

    common_y = sorted(set(ghg_s) & set(trn_s) & set(pwr_s) & set(ren_s))
    for y in common_y:
        fe_panel_rows.append({
            "ISO3": iso,
            "year": y,
            "log_ghg": math.log(max(ghg_s[y], 1.0)),
            "ren_share": ren_s[y],
            "log_trn": math.log(max(trn_s[y], 0.1)),
            "log_pwr": math.log(max(pwr_s[y], 0.1)),
        })

    ly = max(set(ghg_s) & set(trn_s) & set(pwr_s))
    ry = max(ren_s)
    country_latest_rows.append({
        "ISO3": iso,
        "Year": ly,
        "Total_GHG_MtCO2e": round(ghg_s[ly], 2),
        "Transport_CO2_Mt": round(trn_s[ly], 2),
        "Power_CO2_Mt": round(pwr_s[ly], 2),
        "IEA_Renewable_Final_%": round(ren_s[ry], 2),
    })

df_edgar_peers = pd.DataFrame(country_latest_rows)
fe_ren = panel_fixed_effects(fe_panel_rows, entity_col="ISO3", y_col="log_ghg", x_col="ren_share")
fe_pwr = panel_fixed_effects(fe_panel_rows, entity_col="ISO3", y_col="log_ghg", x_col="log_pwr")
eg_trn = cointegration_eg_test(df_tur_edgar["transport_co2_mt"].tolist(), df_tur_edgar["total_ghg_mt"].tolist())

print("\n⚡ 6 Akdeniz/Avrupa Ekonomisinde Gerçek JRC EDGAR Emisyon ve IEA Yenilenebilir Enerji Tablosu:")
print(df_edgar_peers.to_string(index=False))
print(f"\n📊 Sabit Etkiler (FE Within) Panel Regresyonu (N={fe_ren['n_obs']} gerçek gözlem, 6 ülke):")
print(f"   • IEA Yenilenebilir Enerji Payı -> log(GHG) (β_FE) : {fe_ren['beta_fe']:+.5f} (SE = {fe_ren['std_error']:.5f}, t = {fe_ren['t_stat']:.2f}, p = {fe_ren['p_value']:.4e})")
print(f"   • log(Enerji Endüstrisi CO₂) -> log(GHG) (β_FE)    : {fe_pwr['beta_fe']:+.4f} (SE = {fe_pwr['std_error']:.4f}, Within R² = {fe_pwr['r_squared_within']:.4f})")
print(f"   • Türkiye Ulaştırma CO₂ <-> Toplam GHG Eşbütünleşme: ADF t = {eg_trn['engle_granger_adf_t_stat']:.3f}")

# ==============================================================================
# ADIM 2: Türkiye EDGAR Sektörel Emisyonları ve BIST Denizcilik Geçiş VaR Grafiği
# STEP 2: Visualization of Türkiye EDGAR Sectoral Emissions & BIST Maritime VaR
# ==============================================================================
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: Türkiye (TUR) 1970–2024 Gerçek JRC EDGAR Toplam GHG, Enerji ve Ulaştırma CO₂
ax1.plot(df_tur_edgar["year"], df_tur_edgar["total_ghg_mt"], color="#f43f5e", lw=2.3, label="Toplam Sera Gazı (Mt CO₂e)")
ax1.plot(df_tur_edgar["year"], df_tur_edgar["power_co2_mt"], color="#f59e0b", lw=2.0, ls="--", label="Enerji Endüstrisi CO₂ (Mt)")
ax1.plot(df_tur_edgar["year"], df_tur_edgar["transport_co2_mt"], color="#38bdf8", lw=2.0, label="Ulaştırma Sektörü CO₂ (Mt)")
ax1.set_title("A) Türkiye (TUR) JRC EDGAR Sektörel Emisyon Serileri (1970–2024)", color="#f8fafc", fontweight="bold")
ax1.set_ylabel("Emisyon Hacmi (Mt CO₂e / yıl)", color="#cbd5e1")
ax1.legend(facecolor="#0f172a", edgecolor="#334155", labelcolor="#f8fafc", fontsize=8.5)
ax1.grid(alpha=0.18, color="#64748b")

# Panel B: Türkiye (TUR) 1990–2026 BIST Denizcilik İklim Geçiş VaR (%) ve Liman SLR Maruziyeti
yrs_bist = sorted(set(tur_bist_var) & set(tur_port_slr))
ax2.plot(yrs_bist, [tur_bist_var[y] for y in yrs_bist], color="#22c55e", marker="o", lw=2.2, label="BIST Denizcilik İklim Geçiş VaR (%)")
ax2_t = ax2.twinx()
ax2_t.plot(yrs_bist, [tur_port_slr[y] for y in yrs_bist], color="#38bdf8", marker="s", ls="--", lw=2.0, label="Kıyısal Liman SLR Maruziyet İndeksi")
ax2_t.tick_params(colors="#7dd3fc")
ax2.set_title("B) BIST Denizcilik İklim Geçiş VaR ve Liman SLR Riski (1990–2026)", color="#f8fafc", fontweight="bold")
ax2.set_ylabel("BIST İklim Geçiş VaR (%)", color="#22c55e")
ax2_t.set_ylabel("Liman SLR Taşkın Maruziyet İndeksi", color="#38bdf8")
ax2.grid(alpha=0.18, color="#64748b")

fig.suptitle("GOMD Python SDK v2.0.0 — Vaka Çalışması 9: COP31 Enerji Dönüşümü, EDGAR Emisyonları & BIST VaR", color="#ffffff", fontsize=12.5, fontweight="bold", y=1.01)
plt.tight_layout()
fig.savefig("cs09_energy_transition_sectoral_ghg_green_shipping_corridors.png", dpi=140, bbox_inches="tight", facecolor=fig.get_facecolor())
plt.show()
