#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Karadeniz, Marmara ve Akdeniz Balıkçılık Stokları, Akuakültür Yapısal Geçişi ve MEDITS Demersal Biyokütle Dinamikleri (1970–2025)
Black Sea, Marmara & Mediterranean Fisheries Production, Aquaculture Transition & MEDITS Demersal Biomass Dynamics (1970–2025)
==============================================================================
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 FAO Balıkçılık/Akuakültür (1970–2024) ve MEDITS Serileri
# STEP 1: Live Retrieval of FAO Capture/Aquaculture (1970–2024) & MEDITS Basin Series
# ==============================================================================
from gomd.stats import (
    mann_kendall_sen,
    pettitt_changepoint,
    transfer_entropy_causal,
    panel_fixed_effects,
)

# 1. Türkiye (TUR) 1970–2024 gerçek FAO avcılık, akuakültür ve toplam üretim serileri
tur_cap  = fetch_gomd_annual_series("fao_wb_capture_fisheries_mt", entity="TUR", period_from=1970, period_to=2024)
tur_aqua = fetch_gomd_annual_series("fao_wb_aquaculture_production_mt", entity="TUR", period_from=1970, period_to=2024)
tur_tot  = fetch_gomd_annual_series("fao_wb_total_fisheries_production_mt", entity="TUR", period_from=1970, period_to=2024)

fish_years = sorted(set(tur_cap) & set(tur_aqua) & set(tur_tot))
df_tur_fish = pd.DataFrame([
    {
        "year": y,
        "capture_kt": round(tur_cap[y] / 1000.0, 2),
        "aquaculture_kt": round(tur_aqua[y] / 1000.0, 2),
        "total_kt": round(tur_tot[y] / 1000.0, 2),
        "aqua_share_pct": round((tur_aqua[y] / max(tur_tot[y], 1.0)) * 100.0, 2),
    }
    for y in fish_years
])

mk_aqua = mann_kendall_sen(df_tur_fish["aqua_share_pct"].tolist(), t=df_tur_fish["year"].tolist())
pt_aqua = pettitt_changepoint(df_tur_fish["aqua_share_pct"].tolist(), labels=df_tur_fish["year"].tolist())

print(f"\n🐟 Türkiye (TUR) Akuakültür Payı: 1970 = %{df_tur_fish.iloc[0]['aqua_share_pct']:.2f} -> {df_tur_fish.iloc[-1]['year']} = %{df_tur_fish.iloc[-1]['aqua_share_pct']:.2f}")
print(f"⚡ Akuakültür Yapısal Kırılma Yılı (Pettitt) : {pt_aqua['changepoint_label']} (Δ = +{pt_aqua['regime_shift_delta']:.2f} puan, p = {pt_aqua['p_value_approx']:.4e})")

# 2. 5 Deniz Havzasında (1995–2025) Gerçek MEDITS Demersal Biyokütle, SSB ve SAR Analizi
medits_basins = ["BASIN_MARMARA", "BASIN_MED_LEV", "BASIN_MED_AEG", "BASIN_BLACKSEA_W", "BASIN_BLACKSEA_E"]
basin_summary = []
basin_panels = {}
fe_records = []

for b_code in medits_basins:
    bio_s = fetch_gomd_annual_series("medits_demersal_biomass_kg_km2", entity=b_code, period_from=1995, period_to=2025)
    ssb_s = fetch_gomd_annual_series("medits_spawning_stock_ratio", entity=b_code, period_from=1995, period_to=2025)
    sar_s = fetch_gomd_annual_series("medits_swept_area_ratio_sar", entity=b_code, period_from=1995, period_to=2025)
    b_yrs = sorted(set(bio_s) & set(ssb_s) & set(sar_s))
    b_rows = [
        {"basin": b_code, "year": y, "biomass_kg_km2": bio_s[y], "ssb_ratio": ssb_s[y], "sar": sar_s[y]}
        for y in b_yrs
    ]
    basin_panels[b_code] = pd.DataFrame(b_rows)
    fe_records.extend(b_rows)

    mk_b = mann_kendall_sen([bio_s[y] for y in b_yrs], t=b_yrs)
    te_b = transfer_entropy_causal([sar_s[y] for y in b_yrs], [bio_s[y] for y in b_yrs], bins=3)
    latest_ssb = ssb_s[b_yrs[-1]]
    latest_sar = sar_s[b_yrs[-1]]
    kobe_status = (
        "Yeşil (Sürdürülebilir)" if (latest_ssb >= 1.0 and latest_sar <= 1.5)
        else ("Kırmızı (Aşırı Avlanma & Stok Çöküşü)" if (latest_ssb < 0.8 and latest_sar > 1.5) else "Sarı (Geçiş / Baskı Altında)")
    )
    basin_summary.append({
        "Basin": b_code,
        "Biomass_1995": round(bio_s[b_yrs[0]], 1),
        "Biomass_2025": round(bio_s[b_yrs[-1]], 1),
        "Slope_kg_km2_decade": round(mk_b["theil_sen_slope"] * 10.0, 2),
        "SSB_Ratio_2025": round(latest_ssb, 3),
        "SAR_2025": round(latest_sar, 3),
        "TE_SAR_to_Bio_bits": te_b["transfer_entropy_x_to_y_bits"],
        "Kobe_Phase": kobe_status,
    })

df_medits = pd.DataFrame(basin_summary)
fe_medits = panel_fixed_effects(fe_records, entity_col="basin", y_col="biomass_kg_km2", x_col="sar")
print("\n🦀 5 Deniz Havzasında Gerçek GOMD MEDITS Demersal Biyokütle ve Kobe Stok Durumu (1995–2025):")
print(df_medits.to_string(index=False))
print(f"\n📊 MEDITS Dip Trolü SAR -> Demersal Biyokütle Sabit Etkiler (FE) Panel Eğimi : β_FE = {fe_medits['beta_fe']:+.2f} kg/km² (t = {fe_medits['t_stat']:.2f}, p = {fe_medits['p_value']:.4e}, Within R² = {fe_medits['r_squared_within']:.4f})")

# ==============================================================================
# ADIM 2: FAO Balıkçılık/Akuakültür Geçişi ve MEDITS Havza Biyokütle Görselleştirmesi
# STEP 2: Visualization of Türkiye Aquaculture Transition & MEDITS Demersal Biomass
# ==============================================================================
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 FAO Avcılık vs Akuakültür Üretimi (Bin Ton)
ax1.plot(df_tur_fish["year"], df_tur_fish["capture_kt"], color="#38bdf8", lw=2.2, label="Deniz & İçsu Avcılığı (Bin Ton)")
ax1.plot(df_tur_fish["year"], df_tur_fish["aquaculture_kt"], color="#22c55e", lw=2.4, label="Akuakültür Yetiştiriciliği (Bin Ton)")
ax1.axvline(int(pt_aqua["changepoint_label"]), color="#f59e0b", ls=":", lw=1.8, label=f"Pettitt Kırılma ({pt_aqua['changepoint_label']})")
ax1.set_title("A) Türkiye (TUR) Gerçek FAO Avcılık ve Akuakültür Üretimi (1970–2024)", color="#f8fafc", fontweight="bold")
ax1.set_ylabel("Üretim (Bin Metrik Ton)", color="#cbd5e1")
ax1.legend(facecolor="#0f172a", edgecolor="#334155", labelcolor="#f8fafc", fontsize=8.5)
ax1.grid(alpha=0.18, color="#64748b")

# Panel B: 5 Deniz Havzasında MEDITS Demersal Biyokütle Evrimi (1995–2025)
b_colors = {
    "BASIN_MARMARA": "#f43f5e",
    "BASIN_MED_LEV": "#f59e0b",
    "BASIN_MED_AEG": "#38bdf8",
    "BASIN_BLACKSEA_W": "#22c55e",
    "BASIN_BLACKSEA_E": "#a855f7",
}
for b_code, b_df in basin_panels.items():
    ax2.plot(b_df["year"], b_df["biomass_kg_km2"], lw=2.0, color=b_colors[b_code], label=b_code.replace("BASIN_", ""))
ax2.set_title("B) 5 Havzada Gerçek GOMD MEDITS Demersal Biyokütle (1995–2025)", color="#f8fafc", fontweight="bold")
ax2.set_ylabel("Demersal Biyokütle İndeksi (kg/km²)", color="#cbd5e1")
ax2.legend(facecolor="#0f172a", edgecolor="#334155", labelcolor="#f8fafc", fontsize=8)
ax2.grid(alpha=0.18, color="#64748b")

fig.suptitle("GOMD Python SDK v2.0.0 — Vaka Çalışması 6: Gerçek Veri FAO Balıkçılık & MEDITS Demersal Biyokütle", color="#ffffff", fontsize=12.5, fontweight="bold", y=1.01)
plt.tight_layout()
fig.savefig("cs06_blacksea_med_fisheries_biodiversity_medits.png", dpi=140, bbox_inches="tight", facecolor=fig.get_facecolor())
plt.show()
