#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Karadeniz ve Akdeniz Balıkçılığı: FAO Avcılık ve Yetiştiricilik Geçişi, Türlere Göre Av (FAO 37) ve ICCAT Mavi Yüzgeçli Orkinos Yönetimi (1950–2024)
Black Sea & Mediterranean Fisheries: FAO Capture–Aquaculture Transition, Catch by Species (FAO Area 37) & ICCAT Bluefin Tuna Management (1950–2024)
==============================================================================
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):
  - fao_wb_capture_fisheries_mt, fao_wb_aquaculture_production_mt, fao_wb_total_fisheries_production_mt — FAO / Dünya Bankası
  - FAO_CAPTURE_37_ANE/PIL/MAC/BFT_TLW — FAO FishStat, Akdeniz ve Karadeniz (bölge 37) türlere göre avcılık
  - fao_capture_med_blacksea, fao_aquaculture_marine — FAO küresel balıkçılık ve yetiştiricilik üretimi
  - iccat_catch_bft_med — ICCAT Task I, Akdeniz ve Karadeniz mavi yüzgeçli orkinos avı

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: Türkiye su ürünleri üretimi — FAO avcılık ve yetiştiricilik (1970–2024)
# STEP 1: Türkiye fisheries production — FAO capture & aquaculture (1970–2024)
# ==============================================================================
from gomd.stats import mann_kendall_sen, pettitt_changepoint, panel_fixed_effects

tur_cap = fetch_gomd_annual_series("fao_wb_capture_fisheries_mt", "TUR", 1970, 2024)
tur_aqua = fetch_gomd_annual_series("fao_wb_aquaculture_production_mt", "TUR", 1970, 2024)
tur_tot = fetch_gomd_annual_series("fao_wb_total_fisheries_production_mt", "TUR", 1970, 2024)
yrs = sorted(set(tur_cap) & set(tur_aqua) & set(tur_tot))
df_tur = pd.DataFrame({"year": yrs,
                       "capture_kt": [tur_cap[y] / 1e3 for y in yrs],
                       "aquaculture_kt": [tur_aqua[y] / 1e3 for y in yrs],
                       "aqua_share_pct": [100 * tur_aqua[y] / tur_tot[y] for y in yrs]})
mk_aqua = mann_kendall_sen(df_tur["aqua_share_pct"].tolist(), t=yrs)
pt_aqua = pettitt_changepoint(df_tur["aqua_share_pct"].tolist(), labels=yrs)
print(f"\n🐟 Türkiye yetiştiricilik payı: {yrs[0]} %{df_tur['aqua_share_pct'].iloc[0]:.1f} → {yrs[-1]} %{df_tur['aqua_share_pct'].iloc[-1]:.1f}")
print(f"⚡ Pettitt kırılma yılı: {pt_aqua['changepoint_label']} (ortalama {pt_aqua['pre_regime_mean']:.1f} → {pt_aqua['post_regime_mean']:.1f} %, p ≈ {fmt_p(pt_aqua['p_value_approx'])})")

# ==============================================================================
# ADIM 2: Akdeniz ve Karadeniz (FAO bölgesi 37) türlere göre avcılık — Türkiye ve komşu ülkeler
# STEP 2: Mediterranean & Black Sea (FAO area 37) capture by species — Türkiye and peers
# ==============================================================================
species = {"ANE": "Hamsi / European anchovy", "PIL": "Sardalya / Sardine", "MAC": "Uskumru / Atlantic mackerel", "BFT": "Mavi yüzgeçli orkinos / Bluefin tuna"}
sp_tur = {code: fetch_gomd_annual_series(f"FAO_CAPTURE_37_{code}_TLW", "TUR") for code in species}
ane = sp_tur["ANE"]; ane_y = sorted(ane)
mk_ane = mann_kendall_sen([ane[y] for y in ane_y], t=ane_y)
pt_ane = pettitt_changepoint([ane[y] for y in ane_y], labels=ane_y)
cv_recent = float(np.std([ane[y] for y in ane_y if y >= 2005]) / np.mean([ane[y] for y in ane_y if y >= 2005]))
print(f"\n🐠 Türkiye hamsi avcılığı (FAO 37): en yüksek {max(ane.values())/1e3:,.0f} bin t ({max(ane, key=ane.get)}), "
      f"son yıl {ane[ane_y[-1]]/1e3:,.0f} bin t ({ane_y[-1]}); 2005 sonrası değişkenlik katsayısı {cv_recent:.2f}")
print(f"   Pettitt kırılma yılı {pt_ane['changepoint_label']} (p ≈ {fmt_p(pt_ane['p_value_approx'])}); Sen eğimi {mk_ane['theil_sen_slope']/1e3:+.2f} bin t/yıl")

peers = ["TUR", "ITA", "GRC", "ESP", "EGY"]
cap37 = {iso: fetch_gomd_annual_series("fao_capture_med_blacksea", iso) for iso in peers}
rows = []
for iso in peers:
    s = cap37[iso]; yy = sorted(s)
    rows.append({"ISO": iso, "1990": round(s.get(1990, float('nan')) / 1e3), "2010": round(s.get(2010, float('nan')) / 1e3),
                 f"{yy[-1]}": round(s[yy[-1]] / 1e3), "Sen eğimi 2000+ (bin t/yıl)":
                 round(mann_kendall_sen([s[y] for y in yy if y >= 2000], t=[y for y in yy if y >= 2000])["theil_sen_slope"] / 1e3, 2)})
print("\n🌊 Akdeniz ve Karadeniz'de avcılık (bin ton, FAO 37):")
print(pd.DataFrame(rows).to_string(index=False))

# ==============================================================================
# ADIM 3: Mavi yüzgeçli orkinos — ICCAT kurtarma planı (2007) öncesi ve sonrası
# STEP 3: Bluefin tuna — before and after the ICCAT recovery plan (2007)
# ==============================================================================
bft = {iso: fetch_gomd_annual_series("iccat_catch_bft_med", iso) for iso in ("TUR", "ITA", "ESP", "FRA", "GRC")}
bft_rows = []
for iso, s in bft.items():
    pre = [s[y] for y in s if 1997 <= y <= 2006]; post = [s[y] for y in s if 2008 <= y <= 2017]; late = [s[y] for y in s if y >= 2018]
    bft_rows.append({"ISO": iso, "1997–2006 ort. (t)": round(np.mean(pre)) if pre else None,
                     "2008–2017 ort. (t)": round(np.mean(post)) if post else None, "2018+ ort. (t)": round(np.mean(late)) if late else None})
print("\n🐟 ICCAT Akdeniz mavi yüzgeçli orkinos avı (ton):")
print(pd.DataFrame(bft_rows).to_string(index=False))

fe_rows = []
for iso, s in cap37.items():
    a = fetch_gomd_annual_series("fao_aquaculture_marine", iso) if iso != "EGY" else {}
    for y in sorted(set(s) & set(a)):
        if y >= 1990:
            fe_rows.append({"iso": iso, "capture_kt": s[y] / 1e3, "marine_aqua_kt": a[y] / 1e3})
fe = panel_fixed_effects(fe_rows, "iso", "capture_kt", "marine_aqua_kt")
print(f"\n📐 Ülke içi ilişki (1990+): deniz yetiştiriciliği 1 bin t arttığında FAO-37 avcılığı {fe['beta_fe']:+.3f} bin t "
      f"(t = {fe['t_stat']:.2f}, ülke içi R² = {fe['r_squared_within']:.2f}, N = {fe['n_obs']}). Korelasyondur, nedensellik değildir.")

# ==============================================================================
# ADIM 4: 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)

ax1 = axes[0, 0]
ax1.stackplot(df_tur["year"], df_tur["capture_kt"], df_tur["aquaculture_kt"], colors=["#38bdf8", "#22c55e"], labels=["Avcılık", "Yetiştiricilik"], alpha=0.85)
ax1.set_ylabel("bin ton", color="#cbd5e1")
ax1t = ax1.twinx(); ax1t.plot(df_tur["year"], df_tur["aqua_share_pct"], color="#f59e0b", lw=1.8, label="Yetiştiricilik payı (%)")
ax1t.tick_params(colors="#fcd34d")
ax1.set_title("A) Türkiye su ürünleri üretimi (FAO / Dünya Bankası)", color="#f8fafc", fontweight="bold")
h1, l1 = ax1.get_legend_handles_labels(); h2, l2 = ax1t.get_legend_handles_labels(); ax1.legend(h1 + h2, l1 + l2, loc="upper left", **leg)

ax2 = axes[0, 1]
for (code, name), c in zip(species.items(), ["#38bdf8", "#22c55e", "#f59e0b", "#f43f5e"]):
    s = sp_tur[code]; yy = sorted(s); ax2.plot(yy, [s[y] / 1e3 for y in yy], color=c, lw=1.6, label=name)
ax2.set_yscale("log"); ax2.set_ylabel("bin ton (log)", color="#cbd5e1")
ax2.set_title("B) Türkiye: türlere göre avcılık, Akdeniz ve Karadeniz (FAO 37)", color="#f8fafc", fontweight="bold"); ax2.legend(**leg)

ax3 = axes[1, 0]
pal = {"TUR": "#f43f5e", "ITA": "#22c55e", "GRC": "#38bdf8", "ESP": "#f59e0b", "EGY": "#a78bfa", "FRA": "#e2e8f0"}
for iso, s in cap37.items():
    yy = sorted(s); ax3.plot(yy, [s[y] / 1e3 for y in yy], color=pal[iso], lw=1.6, label=iso)
ax3.set_ylabel("bin ton", color="#cbd5e1")
ax3.set_title("C) FAO 37 bölgesinde toplam avcılık, ülkelere göre", color="#f8fafc", fontweight="bold"); ax3.legend(**leg)

ax4 = axes[1, 1]
for iso, s in bft.items():
    yy = sorted(s); ax4.plot(yy, [s[y] for y in yy], color=pal[iso], lw=1.6, label=iso)
ax4.axvline(2007, color="#e2e8f0", ls=":", lw=1.4, label="ICCAT kurtarma planı (2007)")
ax4.set_ylabel("ton", color="#cbd5e1")
ax4.set_title("D) Akdeniz mavi yüzgeçli orkinos avı (ICCAT Task I)", color="#f8fafc", fontweight="bold"); ax4.legend(**leg)

fig.suptitle("GOMD — Vaka Çalışması 6: Karadeniz ve Akdeniz balıkçılığı, yetiştiricilik geçişi ve orkinos yönetimi (gerçek veri)", color="#ffffff", fontsize=12.5, fontweight="bold")
plt.tight_layout()
fig.savefig("cs06_blacksea_med_fisheries_biodiversity_medits.png", dpi=140, bbox_inches="tight", facecolor=fig.get_facecolor())
plt.show()
