# screenshot: 1000x600
"""Города России: размер — численность населения, цвет — административный статус.

Цвет на двумерной карте значков может передавать и КАЧЕСТВЕННЫЙ признак.
Тогда нужна качественная шкала: разные цветовые тоны без «больше/меньше».
Статус взят из поля featurecla набора Natural Earth: Admin-0 capital —
столица, Admin-1 capital — административный центр региона. Natural Earth
относит к ним и центры бывших автономных округов, поэтому подпись в легенде —
«по данным Natural Earth». Показаны города от 50 тыс. жителей.
"""
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_legend, add_title, fmt, plain_attribution

DATA = Path(__file__).resolve().parents[2] / "data"
cities = gpd.read_file(DATA / "cities.geojson")
ru = cities[(cities["iso_a3"] == "RUS") & (cities["pop_max"] >= 50_000)]

STATUS = {  # featurecla → (подпись, цвет); качественная шкала
    "Admin-0 capital": ("столица", "#d7301f"),
    "Admin-1 capital": ("адм. центр региона", "#2c7fb8"),
    "Populated place": ("прочие города", "#9e9e9e"),
}

max_pop, max_r = ru["pop_max"].max(), 26
m = folium.Map(location=[60, 92], zoom_start=3, tiles="Esri.WorldGrayCanvas")
for _, c in ru.sort_values("pop_max", ascending=False).iterrows():
    label, color = STATUS[c["featurecla"]]
    folium.CircleMarker(
        location=[c["latitude"], c["longitude"]],
        radius=max(max_r * np.sqrt(c["pop_max"] / max_pop), 1.5),
        color="white", weight=0.7, fill=True, fill_color=color, fill_opacity=0.85,
        tooltip=f"<b>{c['name_ru']}</b> ({label})<br>{fmt(c['pop_max'])} чел.",
    ).add_to(m)

svg = '<svg width="150" height="64">'
for value, label in [(1e7, "10 млн"), (3e6, "3 млн"), (5e5, "500 тыс.")]:
    r = max_r * np.sqrt(value / max_pop)
    top = 60 - 2 * r
    svg += (f'<circle cx="32" cy="{60 - r}" r="{r}" fill="none" stroke="#333"/>'
            f'<line x1="32" y1="{top}" x2="74" y2="{top}" stroke="#333" stroke-dasharray="2 2"/>'
            f'<text x="78" y="{top + 4}" font-size="11">{label}</text>')
add_html(m, f"<b>Население, чел.</b><br>{svg}</svg>", position="bottomleft")
add_legend(m, "Статус (по Natural Earth)", [v[1] for v in STATUS.values()],
           [v[0] for v in STATUS.values()], shape="circle")
add_title(m, "Города России от 50 тыс. жителей", "размер — численность, цвет — статус")
plain_attribution(m)
m.save("03_russia_cities.html")
