"""Cherche sur Wikimedia Commons une photo par lieu, avec sa licence et son auteur.
On ne garde que les licences réutilisables, et on imprime les candidats pour relecture."""
import json, subprocess, urllib.parse, re, html, sys

UA = "BeninMapBuilder/1.0 (carte pedagogique; contact: local)"
API = "https://commons.wikimedia.org/w/api.php"

OK_LIC = ("cc0", "cc-by", "cc by", "public domain", "pd-", "cc-zero", "attribution")
# On teste des mots entiers : "nc-" ne se trouve pas dans "cc by-nc 4.0",
# qui passait donc le filtre et se faisait accepter par "cc by".
BAD_LIC = ("non-commercial", "fair use")
BAD_MOT = re.compile(r"\b(nc|nd)\b")

QUERIES = {
 "grand-popo":  ["Grand-Popo Benin beach", "Grand-Popo", "Bouche du Roy Benin"],
 "ouidah":      ["Porte du Non Retour Ouidah", "Ouidah Benin", "Temple des pythons Ouidah"],
 "cotonou":     ["Cotonou Benin", "Dantokpa market Cotonou", "Cotonou city"],
 "ganvie":      ["Ganvie", "Ganvié Benin stilt village", "Lake Nokoue Ganvie"],
 "porto-novo":  ["Porto-Novo Benin mosque", "Porto-Novo Benin", "Grande mosquee Porto Novo"],
 "aheme":       ["Lac Aheme Benin", "Possotome Benin", "Lake Aheme"],
 "ketou":       ["Ketou Benin", "Gelede mask Benin", "Ketou"],
 "lama":        ["Foret de la Lama Benin", "Lama forest Benin", "Benin forest"],
 "abomey":      ["Royal Palaces of Abomey", "Abomey Benin palace", "Abomey bas-relief"],
 "dassa":       ["Dassa-Zoume Benin", "Dassa Zoume", "Dassa hills Benin"],
 "parakou":     ["Parakou Benin", "Parakou market", "Parakou city Benin"],
 "nikki":       ["Nikki Benin Gaani", "Nikki Benin", "Bariba horsemen Benin"],
 "djougou":     ["Djougou Benin", "Djougou", "Djougou market"],
 "kota":        ["Chutes de Kota Benin", "Kota waterfalls Benin", "Kota falls Natitingou"],
 "boukoumbe":   ["Tata Somba Benin", "Boukoumbe Benin", "Batammariba house Benin"],
 "natitingou":  ["Natitingou Benin", "Natitingou", "Atacora Benin landscape"],
 "tanougou":    ["Tanougou waterfall Benin", "Chutes de Tanougou", "Tanougou"],
 "pendjari":    ["Pendjari National Park", "Pendjari elephant", "Pendjari lion Benin"],
 "parc-w":      ["W National Park Benin", "Parc W Benin", "W National Park elephant"],
 "malanville":  ["Malanville Benin", "Niger river Benin", "Malanville"],
}


def api(params):
    url = API + "?" + urllib.parse.urlencode(params)
    out = subprocess.run(["curl", "-sL", "-m", "40", "-A", UA, url],
                         capture_output=True).stdout
    try:
        return json.loads(out)
    except Exception:
        return {}


def clean(s):
    s = re.sub(r"<[^>]+>", "", s or "")
    return html.unescape(s).strip()


def search(term, limit=12):
    d = api({"action": "query", "generator": "search", "gsrsearch": term,
             "gsrnamespace": "6", "gsrlimit": str(limit),
             "prop": "imageinfo", "iiprop": "url|mime|size|extmetadata",
             "iiurlwidth": "900", "format": "json"})
    pages = (d.get("query") or {}).get("pages") or {}
    out = []
    for p in pages.values():
        ii = (p.get("imageinfo") or [{}])[0]
        if ii.get("mime") not in ("image/jpeg", "image/png"):
            continue
        if (ii.get("width") or 0) < 900:
            continue
        m = ii.get("extmetadata") or {}
        lic = clean(m.get("LicenseShortName", {}).get("value", "")) or \
              clean(m.get("License", {}).get("value", ""))
        low = lic.lower()
        if any(b in low for b in BAD_LIC) or BAD_MOT.search(low):
            continue
        if not any(k in low for k in OK_LIC):
            continue
        out.append({
            "title": p["title"].replace("File:", ""),
            "thumb": ii.get("thumburl"),
            "page": ii.get("descriptionurl"),
            "license": lic,
            "author": clean(m.get("Artist", {}).get("value", "")) or "auteur non précisé",
            "desc": clean(m.get("ImageDescription", {}).get("value", ""))[:120],
            "w": ii.get("width"), "h": ii.get("height"),
            "index": p.get("index", 99),
        })
    out.sort(key=lambda x: x["index"])
    return out


res = {}
for sid, terms in QUERIES.items():
    found = []
    for t in terms:
        for c in search(t):
            if c["title"] not in [f["title"] for f in found]:
                found.append(c)
        if len(found) >= 6:
            break
    res[sid] = found[:6]
    print(f"\n=== {sid} ({len(found)} candidats) ===")
    for c in found[:6]:
        print(f"  · {c['title'][:78]}")
        print(f"      {c['license']} | {c['author'][:60]} | {c['w']}x{c['h']}")
    sys.stdout.flush()

json.dump(res, open("photo_candidates.json", "w"), ensure_ascii=False, indent=1)
print("\n-> photo_candidates.json")
