# screenshot: 1000x560
"""Абсолютные и относительные показатели на одной карте — правильно.

Относительный показатель (плотность) — картограммой (цветом территорий).
Абсолютный показатель (численность) — пропорциональными кругами.
В отечественной картографии такое сочетание называют
«картограмма + картодиаграмма».
"""
import sys
from pathlib import Path

import folium
import geopandas as gpd
import numpy as np
from branca.utilities import color_brewer

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from maptools import add_html, add_legend, 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"]

# 1) картограмма плотности
breaks = [0, 10, 30, 60, 100, 200, 2000]
labels = ["< 10", "10–30", "30–60", "60–100", "100–200", "> 200"]
colors = color_brewer("Greens", 6)
world = world.assign(color=[colors[c] for c in np.digitize(world["pop_density"], breaks[1:-1])])

m = folium.Map(location=[30, 20], zoom_start=2, tiles="Esri.WorldGrayCanvas")
folium.GeoJson(
    world[["name_ru", "color", "geometry"]],
    style_function=lambda f: {"fillColor": f["properties"]["color"], "color": "white",
                              "weight": 0.5, "fillOpacity": 0.85},
).add_to(m)

# 2) круги: ПЛОЩАДЬ круга пропорциональна населению => радиус ~ корень из значения
centers = world.to_crs("ESRI:54009").representative_point().to_crs(4326)
max_pop, max_radius = world["pop_est"].max(), 40  # самый большой круг — 40 px
for (_, row), pt in zip(world.iterrows(), centers):
    r = max_radius * np.sqrt(row["pop_est"] / max_pop)
    if r < 2:
        continue
    folium.CircleMarker(
        location=[pt.y, pt.x], radius=r,
        color="#3d1f50", weight=1, fill=True, fill_color="#8e5bb0", fill_opacity=0.45,
        tooltip=f"{row['name_ru']}: {fmt(row['pop_est'] / 1e6, 1)} млн чел.",
    ).add_to(m)

# вложенная легенда размеров: круги стоят на общем основании,
# подписи вынесены вправо на уровень верхней точки каждого круга
svg = '<svg width="150" height="86">'
for value, label in [(1e9, "1 млрд"), (3e8, "300 млн"), (5e7, "50 млн")]:
    r = max_radius * np.sqrt(value / max_pop)
    top = 82 - 2 * r
    svg += (f'<circle cx="40" cy="{82 - r}" r="{r}" fill="#8e5bb0" fill-opacity="0.15" stroke="#3d1f50"/>'
            f'<line x1="40" y1="{top}" x2="88" y2="{top}" stroke="#3d1f50" stroke-dasharray="2 2"/>'
            f'<text x="92" y="{top + 4}" font-size="11">{label}</text>')
svg += "</svg>"
add_html(m, f"<b>Население, чел.</b><br>{svg}", position="bottomleft")
add_legend(m, "Плотность, чел./км²", colors[::-1], labels[::-1])
add_title(m, "Население мира", "цвет — плотность, круги — численность")
plain_attribution(m)  # убираем флажок из подписи Leaflet
m.save("04_counts_as_symbols.html")
