# screenshot: 1000x600
"""Ступенчатые значки 3 × 3: и размер, и цвет разбиты на классы.

Население — 3 ступени размера, ВВП на душу — 3 ступени цвета.
Получается 9 вариантов знака, и легенда становится матрицей 3 × 3:
читатель находит в ней сочетание «крупная + бедная», «мелкая + богатая» и т. п.
"""
import sys
from pathlib import Path

import folium
import geopandas as gpd
import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from maptools import add_html, add_title, fmt, plain_attribution

DATA = Path(__file__).resolve().parents[2] / "data"
world = gpd.read_file(DATA / "countries.geojson")
world = world[(world["iso_a3"] != "ATA") & world["gdp_per_capita"].notna()].copy()

# классы размера (население) и цвета (ВВП на душу)
SIZE_BREAKS, RADII = [20e6, 100e6], [5, 11, 19]
SIZE_LABELS = ["< 20", "20–100", "> 100"]  # млн чел.
COLOR_BREAKS, COLORS = [4000, 20000], ["#fdcc8a", "#fc8d59", "#b30000"]  # OrRd
COLOR_LABELS = ["< 4 тыс.", "4–20 тыс.", "> 20 тыс."]

world["s"] = np.digitize(world["pop_est"], SIZE_BREAKS)        # 0, 1, 2
world["c"] = np.digitize(world["gdp_per_capita"], COLOR_BREAKS)  # 0, 1, 2
world["pt"] = world.to_crs("ESRI:54009").representative_point().to_crs(4326)

m = folium.Map(location=[25, 15], zoom_start=2, tiles="Esri.WorldGrayCanvas")
for _, row in world.sort_values("pop_est", ascending=False).iterrows():
    folium.CircleMarker(
        location=[row["pt"].y, row["pt"].x], radius=RADII[row["s"]],
        color="#3b2a20", weight=0.8, fill=True, fill_color=COLORS[row["c"]], fill_opacity=0.9,
        tooltip=(f"<b>{row['name_ru']}</b><br>{fmt(row['pop_est'] / 1e6, 1)} млн чел., "
                 f"{fmt(row['gdp_per_capita'])} долл./чел."),
    ).add_to(m)

# легенда-матрица: строки — цвет (ВВП на душу), столбцы — размер (население)
cell = 44
svg = f'<svg width="{80 + 3 * cell}" height="{3 * cell + 34}" font-size="11">'
for j, lab in enumerate(SIZE_LABELS):
    svg += f'<text x="{80 + j * cell + cell / 2}" y="{3 * cell + 14}" text-anchor="middle">{lab}</text>'
for i, lab in enumerate(COLOR_LABELS[::-1]):           # сверху — самые богатые
    c = len(COLORS) - 1 - i
    svg += f'<text x="74" y="{i * cell + cell / 2 + 4}" text-anchor="end">{lab}</text>'
    for j, r in enumerate(RADII):
        svg += (f'<circle cx="{80 + j * cell + cell / 2}" cy="{i * cell + cell / 2}" r="{r}" '
                f'fill="{COLORS[c]}" stroke="#3b2a20" stroke-width="0.8"/>')
svg += f'<text x="{80 + 1.5 * cell}" y="{3 * cell + 30}" text-anchor="middle" fill="#555">население, млн чел. →</text></svg>'
add_html(m, f"<b>ВВП на душу, долл. ↑</b><br>{svg}", position="bottomleft")
add_title(m, "Население × ВВП на душу", "3 ступени размера × 3 ступени цвета")
plain_attribution(m)
m.save("02_graduated_3x3.html")
