# -*- coding: utf-8 -*-
"""Renderira PNG kartu za svaku rutu (Carto podloga + trag) u img/ — za Prilog 1 PDF."""
import json, os, time
from staticmap import StaticMap, Line, CircleMarker
from PIL import ImageDraw, ImageFont

BASE = os.path.dirname(os.path.abspath(__file__))
os.makedirs(os.path.join(BASE, "img"), exist_ok=True)
cfg = json.load(open(os.path.join(BASE, "rute.json"), encoding="utf-8"))
COLORS = {"R1": "#d62728", "R2": "#2ca02c", "R3": "#1f77b4", "R4": "#ff7f0e",
          "R5": "#9467bd", "R6": "#0e8585", "R7": "#8c564b", "R8": "#d63384"}
TILES = "https://a.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}.png"
ATTR = "© OpenStreetMap contributors © CARTO"

def thin(coords, max_pts=500):
    if len(coords) <= max_pts:
        return coords
    step = len(coords) / max_pts
    out = [coords[int(i * step)] for i in range(max_pts)]
    out.append(coords[-1])
    return out

def attribution(img):
    d = ImageDraw.Draw(img)
    try:
        f = ImageFont.truetype("/System/Library/Fonts/Supplemental/Arial.ttf", 18)
    except Exception:
        f = ImageFont.load_default()
    tw = d.textlength(ATTR, font=f)
    x, y = img.width - tw - 12, img.height - 30
    d.rectangle([x - 6, y - 3, img.width - 4, y + 23], fill=(255, 255, 255, 220))
    d.text((x, y), ATTR, fill=(90, 90, 90), font=f)
    return img

def render(tracks, out, w=1600, h=1000):
    m = StaticMap(w, h, url_template=TILES, padding_x=60, padding_y=60)
    for coords, color in tracks:
        pts = [(c[0], c[1]) for c in thin(coords)]
        m.add_line(Line(pts, "white", 11))           # bijeli halo
        m.add_line(Line(pts, color, 6))
    for coords, color in tracks:
        m.add_marker(CircleMarker((coords[0][0], coords[0][1]), "white", 18))
        m.add_marker(CircleMarker((coords[0][0], coords[0][1]), "#1a3e5c", 12))
    img = m.render()
    attribution(img).save(out)
    print("OK", out, f"{os.path.getsize(out)//1024} KB")

all_tracks = []
for r in cfg["rute"]:
    p = os.path.join(BASE, "geojson", f"{r['id'].lower()}.geojson")
    gj = json.load(open(p, encoding="utf-8"))
    coords = gj["features"][0]["geometry"]["coordinates"]
    all_tracks.append((coords, COLORS[r["id"]]))
    render([(coords, COLORS[r["id"]])], os.path.join(BASE, "img", f"{r['id'].lower()}.png"))
    time.sleep(1)

render(all_tracks, os.path.join(BASE, "img", "pregled.png"), 1600, 1100)
