#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ulusal Deniz Ticaret Filoları Karbonsuzlaştırma Madenciliği: Gerçek UNCTAD Filo Tonajı, IMO CII, AB Denizcilik ETS (2023/959), FuelEU Maritime ve AIS Hız Optimizasyonu (1990–2026)
National Merchant Fleet Decarbonization Mining: Real UNCTAD Fleet DWT, IMO CII, Maritime EU ETS (2023/959), FuelEU Maritime & AIS Speed-Power Optimization (1990–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 8 Denizci Ülkenin Gerçek Filo ve Emisyon Verisi
# STEP 1: Fetch Real UNCTAD Fleet DWT, IMO CII, EU ETS & FuelEU Series from GOMD
# ==============================================================================
from gomd.maritime import (
    calculate_imo_cii,
    calculate_eu_ets_exposure,
    calculate_fueleu_maritime,
    imo_2023_strive_trajectory,
    ais_speed_power_emissions,
    poseidon_principles_alignment,
    psc_detention_risk_score,
)
from gomd.stats import mann_kendall_sen

countries = ["TUR", "GRC", "ITA", "ESP", "FRA", "DEU", "NOR", "CHN"]

# Türkiye (TUR) ve Küresel (WLD) için 1990-2026 gerçek karbonsuzlaştırma serileri
tur_aer   = fetch_gomd_annual_series("imo_cii_fleet_aer", entity="TUR", period_from=1990, period_to=2026)
tur_ets   = fetch_gomd_annual_series("eu_ets_shipping_surrender_mt_co2", entity="TUR", period_from=1990, period_to=2026)
tur_feu   = fetch_gomd_annual_series("fueleu_maritime_wtw_intensity", entity="TUR", period_from=1990, period_to=2026)
tur_eexi  = fetch_gomd_annual_series("imo_eedi_eexi_attainment_pct", entity="TUR", period_from=1990, period_to=2026)
tur_zfuel = fetch_gomd_annual_series("green_corridor_zero_emission_fuel_share_pct", entity="TUR", period_from=1990, period_to=2026)

# 8 ülkenin son yıl gerçek GOMD gözlemlerini çekerek ülke filosu denetim tablosu oluşturma
fleet_audit_rows = []
for iso in countries:
    aer_s  = fetch_gomd_annual_series("imo_cii_fleet_aer", entity=iso, period_from=2008, period_to=2026)
    ets_s  = fetch_gomd_annual_series("eu_ets_shipping_surrender_mt_co2", entity=iso, period_from=2020, period_to=2026)
    feu_s  = fetch_gomd_annual_series("fueleu_maritime_wtw_intensity", entity=iso, period_from=2020, period_to=2026)
    eexi_s = fetch_gomd_annual_series("imo_eedi_eexi_attainment_pct", entity=iso, period_from=2020, period_to=2026)
    bulk_s = fetch_gomd_annual_series("unctad_fleet_dwt_bulk_carriers", entity=iso, period_from=2018, period_to=2026)
    tank_s = fetch_gomd_annual_series("unctad_fleet_dwt_oil_tankers", entity=iso, period_from=2018, period_to=2026)
    cont_s = fetch_gomd_annual_series("unctad_fleet_dwt_container", entity=iso, period_from=2018, period_to=2026)
    age_s  = fetch_gomd_annual_series("unctad_fleet_age_avg", entity=iso, period_from=2018, period_to=2026)

    aer_2008 = aer_s.get(2008, list(aer_s.values())[0])
    aer_2026 = aer_s[max(aer_s)]
    ets_mt   = ets_s[max(ets_s)]
    wtw_2026 = feu_s[max(feu_s)]
    eexi_pct = eexi_s[max(eexi_s)]
    bulk_dwt = bulk_s[max(bulk_s)]
    tank_dwt = tank_s[max(tank_s)]
    cont_dwt = cont_s[max(cont_s)]
    avg_age  = age_s[max(age_s)]
    total_dwt = bulk_dwt + tank_dwt + cont_dwt

    # Baskın filo segmentini gerçek UNCTAD DWT payına göre belirle
    dom_type = "bulk_carrier" if bulk_dwt >= max(tank_dwt, cont_dwt) else ("tanker" if tank_dwt >= cont_dwt else "container")
    rep_dwt  = 82000.0 if dom_type == "bulk_carrier" else (110000.0 if dom_type == "tanker" else 68000.0)
    rep_dist = 56000.0
    # Gerçek GOMD imo_cii_fleet_aer değerine karşılık gelen temsilci gemi yakıt tüketimi (ton VLSFO)
    rep_fuel_t = (aer_2026 * rep_dwt * rep_dist) / (3.151 * 1e6)

    cii = calculate_imo_cii(
        fuel_consumption_tonnes={"vlsfo": rep_fuel_t},
        dwt_or_gt=rep_dwt,
        distance_nm=rep_dist,
        ship_type=dom_type,
        year=2026,
    )
    ets = calculate_eu_ets_exposure(
        co2_tonnes=ets_mt * 1e6,
        voyage_scope="extra_eu" if iso in ("TUR", "CHN", "NOR") else "intra_eu",
        year=2026,
        eua_price_eur=78.5,
    )
    ghg = imo_2023_strive_trajectory(
        baseline_2008_aer=aer_2008,
        current_aer=aer_2026,
        annual_emissions_tco2e=ets_mt * 1e6,
        annual_efficiency_gain_pct=2.1,
        current_year=2026,
    )
    pos = poseidon_principles_alignment(
        attained_aer=aer_2026,
        required_trajectory_aer=cii["required_cii_g_dwt_nm"],
        loan_outstanding_usd=100_000_000.0,
    )
    psc = psc_detention_risk_score(
        ship_age_years=avg_age,
        flag_tier="white",
        ro_performance="high",
        deficiencies_36m=max(1, int(round((100.0 - eexi_pct) / 6.0))),
        detentions_36m=1 if avg_age > 15.0 else 0,
        ship_type=dom_type,
    )

    fleet_audit_rows.append({
        "ISO3": iso,
        "UNCTAD_Core_DWT_M": round(total_dwt / 1e6, 2),
        "Fleet_Age_Yr": round(avg_age, 2),
        "GOMD_AER_2026": round(aer_2026, 3),
        "CII_Rating": cii["cii_rating"],
        "EEXI_Attain_%": round(eexi_pct, 1),
        "FuelEU_WtW": round(wtw_2026, 2),
        "EU_ETS_MtCO2": round(ets_mt, 3),
        "ETS_Cost_MEUR": round(ets["estimated_ets_cost_eur"] / 1e6, 2),
        "Stranded_Yr": ghg["stranded_asset_year_strive"],
        "Poseidon_Delta_%": pos["alignment_delta_pct"],
        "PSC_Risk_%": psc["estimated_detention_risk_pct"],
    })

df_fleet = pd.DataFrame(fleet_audit_rows)
print("\n⚓ 8 Denizci Ülkenin Gerçek GOMD Verilerine Dayalı 2026 Karbonsuzlaştırma Denetim Tablosu:")
print(df_fleet.to_string(index=False))

# ==============================================================================
# ADIM 2: Türkiye (TUR) 1990–2026 Filo Karbonsuzlaştırma Zaman Serisi ve AIS Hız Eğrisi
# STEP 2: Türkiye (TUR) 1990–2026 Decarbonization Trajectory & AIS Speed Optimization
# ==============================================================================
tur_years = sorted(set(tur_aer) & set(tur_ets) & set(tur_feu) & set(tur_eexi) & set(tur_zfuel))
df_tur_ts = pd.DataFrame([
    {
        "year": y,
        "aer_gco2_dwt_nm": tur_aer[y],
        "ets_mt_co2": tur_ets[y],
        "fueleu_wtw": tur_feu[y],
        "eexi_pct": tur_eexi[y],
        "zero_fuel_pct": tur_zfuel[y],
    }
    for y in tur_years
])
mk_aer = mann_kendall_sen(df_tur_ts["aer_gco2_dwt_nm"].tolist(), t=df_tur_ts["year"].tolist())
print(f"\n📉 Türkiye (TUR) 1990–2026 Filo AER Trendi: {mk_aer['theil_sen_slope']*10:.3f} gCO₂/DWT·nm / 10-yıl (p = {mk_aer['p_value']:.2e})")

# Türkiye UNCTAD Dökme Yük Filosu Temsilci Gemisi İçin AIS Seyir Hızı Optimizasyonu
speeds = np.linspace(10.5, 16.0, 12)
speed_rows = []
for spd in speeds:
    voyage_hrs = 56000.0 / float(spd)
    sim = ais_speed_power_emissions(
        mcr_kw=12800.0,
        design_speed_kn=14.5,
        observed_speed_kn=float(spd),
        design_draft_m=14.2,
        observed_draft_m=13.4,
        voyage_hours=voyage_hrs,
        aux_power_kw=620.0,
        weather_fouling_margin=1.12,
        sfoc_g_kwh=171.0,
    )
    cii_sim = calculate_imo_cii(
        fuel_consumption_tonnes=sim["fuel_consumption_tonnes"],
        dwt_or_gt=82000.0,
        distance_nm=56000.0,
        ship_type="bulk_carrier",
        fuel_type="vlsfo",
        year=2026,
    )
    speed_rows.append({
        "speed_knots": round(float(spd), 2),
        "fuel_tonnes": sim["fuel_consumption_tonnes"],
        "co2_tonnes": sim["co2_emissions_tonnes"],
        "aer": cii_sim["attained_aer_g_dwt_nm"],
        "cii_rating": cii_sim["cii_rating"],
    })
df_speed = pd.DataFrame(speed_rows)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13.5, 5.2), 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) Gerçek GOMD Filo AER ve EEDI/EEXI Uyum Oranı (1990–2026)
ax1.plot(df_tur_ts["year"], df_tur_ts["aer_gco2_dwt_nm"], color="#38bdf8", marker="o", lw=2.2, label="Türkiye Filo AER (gCO₂/DWT·nm)")
ax1_t = ax1.twinx()
ax1_t.plot(df_tur_ts["year"], df_tur_ts["eexi_pct"], color="#22c55e", marker="s", ls="--", lw=2.0, label="EEDI/EEXI Uyum Oranı (%)")
ax1_t.tick_params(colors="#86efac")
ax1.set_title("A) Türkiye (TUR) Filo Karbon Yoğunluğu (AER) & EEXI Uyumu (1990–2026)", color="#f8fafc", fontweight="bold")
ax1.set_xlabel("Yıl", color="#cbd5e1")
ax1.set_ylabel("Filo AER (gCO₂/DWT·nm)", color="#38bdf8")
ax1_t.set_ylabel("IMO EEDI/EEXI Uyum (%)", color="#22c55e")
ax1.grid(alpha=0.18, color="#64748b")

# Panel B: 8 Denizci Ülkenin 2026 Gerçek GOMD AB ETS Karbon Maliyeti ve CII AER Karşılaştırması
x_pos = np.arange(len(df_fleet))
ax2.bar(x_pos, df_fleet["ETS_Cost_MEUR"], width=0.55, color="#f59e0b", edgecolor="#ffffff", linewidth=0.6, label="2026 AB ETS Tahsisat Maliyeti (Milyon EUR)")
ax2.set_xticks(x_pos)
ax2.set_xticklabels(df_fleet["ISO3"], fontsize=9.5, fontweight="bold")
ax2.set_title("B) 8 Denizci Ülkenin Gerçek GOMD 2026 AB ETS Maliyetleri (Milyon EUR)", color="#f8fafc", fontweight="bold")
ax2.set_ylabel("AB ETS Maliyeti (Milyon EUR)", color="#cbd5e1")
ax2.legend(facecolor="#0f172a", edgecolor="#334155", labelcolor="#f8fafc", fontsize=8.5)
ax2.grid(alpha=0.18, color="#64748b")

fig.suptitle("GOMD Python SDK v2.0.0 — Vaka Çalışması 2: Gerçek UNCTAD Filo & IMO CII/ETS Karbonsuzlaştırma", color="#ffffff", fontsize=12.5, fontweight="bold", y=1.01)
plt.tight_layout()
fig.savefig("cs02_maritime_decarbonization_cii_ets_fueleu.png", dpi=140, bbox_inches="tight", facecolor=fig.get_facecolor())
plt.show()
