#!/usr/bin/env python3
"""
Ambil foto asli tiap unit (Wikimedia Commons, lisensi bebas) lalu pasang ke web, API, dan Flutter.
Jalankan SEKALI dari folder multi-point-107 (butuh internet, Python 3 bawaan Mac sudah cukup):

    python3 ambil-foto.py            -> foto disimpan sebagai file di web/img/unit/
    python3 ambil-foto.py --embed    -> foto ditanam langsung di index.html (satu file, cocok untuk kiosk/offline)

Hasil:
  web/img/unit/<id>.jpg             foto untuk website (index.html langsung memakainya)
  api/uploads/units/<id>.jpg        foto untuk API / aplikasi
  database/foto_unit.sql            UPDATE vehicles (photo_url + atribusi) -> import di phpMyAdmin
  mobile/assets/units/<id>.jpg      foto cadangan di dalam aplikasi (tampil walau API belum punya foto)
  web/img/unit/KREDIT.txt           daftar atribusi (wajib untuk lisensi CC BY-SA)

Mau pakai foto armada sendiri? Taruh file <id>.jpg di web/img/unit/ lalu jalankan:  python3 ambil-foto.py --lokal
"""
import base64, json, os, re, shutil, sys, time, urllib.parse, urllib.request

ROOT = os.path.dirname(os.path.abspath(__file__))
UA = "MultiPoint107-PhotoSync/1.0 (sewa@ptsatukosongtujuh.com)"   # wajib menurut kebijakan Wikimedia
WIKI = os.environ.get("WIKI_HOST", "https://{lang}.wikipedia.org")
COMMONS = os.environ.get("COMMONS_HOST", "https://commons.wikimedia.org")

# id unit -> judul artikel Wikipedia (dicoba berurutan, en lalu id)
UNIT = {
    "agya":     ["Toyota Agya", "Daihatsu Ayla"],
    "brio":     ["Honda Brio"],
    "avanza":   ["Toyota Avanza"],
    "ertiga":   ["Suzuki Ertiga"],
    "xpander":  ["Mitsubishi Xpander"],
    "xl7":      ["Suzuki XL7", "Suzuki Ertiga"],
    "fortuner": ["Toyota Fortuner"],
    "ayla":     ["Daihatsu Ayla"],
    "innova":   ["Toyota Innova"],
    "alphard":  ["Toyota Alphard"],
    "pajero":   ["Mitsubishi Pajero Sport"],
    "hiace":    ["Toyota HiAce"],
    "elf":      ["Isuzu Elf"],
    "ioniq5":   ["Hyundai Ioniq 5"],
    "cloudev":  ["Wuling Cloud EV", "Baojun Yunduo"],
}


def get(url, raw=False):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=40) as r:
        data = r.read()
    return data if raw else json.loads(data.decode("utf-8"))


def find_photo(titles):
    """Foto utama artikel (pageimages hanya mengembalikan gambar berlisensi bebas)."""
    for lang in ("en", "id"):
        for title in titles:
            q = urllib.parse.urlencode({
                "action": "query", "format": "json", "formatversion": 2, "redirects": 1,
                "prop": "pageimages", "piprop": "thumbnail|name", "pithumbsize": 1000, "titles": title,
            })
            try:
                page = (get(WIKI.format(lang=lang) + "/w/api.php?" + q).get("query", {}).get("pages") or [{}])[0]
            except Exception as e:
                print(f"   ({lang}:{title} gagal: {e})")
                continue
            if page.get("thumbnail", {}).get("source"):
                return page["thumbnail"]["source"], page.get("pageimage", "")
    return None, None


def credit_of(file_name):
    q = urllib.parse.urlencode({"action": "query", "format": "json", "formatversion": 2, "prop": "imageinfo",
                                "iiprop": "extmetadata", "titles": "File:" + file_name})
    try:
        meta = get(COMMONS + "/w/api.php?" + q)["query"]["pages"][0]["imageinfo"][0]["extmetadata"]
        artist = re.sub(r"<[^>]+>", "", meta.get("Artist", {}).get("value", "Unknown")).strip()
        lic = meta.get("LicenseShortName", {}).get("value", "lihat Commons")
    except Exception:
        artist, lic = "Unknown", "lihat Commons"
    return f"Foto: {artist} / {lic} / Wikimedia Commons (File:{file_name})"[:250]


def patch_index(mapping):
    path = os.path.join(ROOT, "web", "index.html")
    html = open(path, encoding="utf-8").read()
    new = re.sub(r"/\*FOTO_LOKAL\*/.*?/\*END_FOTO_LOKAL\*/",
                 lambda _: "/*FOTO_LOKAL*/" + json.dumps(mapping, ensure_ascii=False) + "/*END_FOTO_LOKAL*/",
                 html, count=1, flags=re.S)
    if new == html and mapping:
        sys.exit("!! Penanda FOTO_LOKAL tidak ditemukan di web/index.html — pakai index.html dari paket terbaru.")
    open(path, "w", encoding="utf-8").write(new)


def sql_escape(s):
    return s.replace("\\", "\\\\").replace("'", "''")


def main():
    embed = "--embed" in sys.argv
    local_only = "--lokal" in sys.argv
    web_dir = os.path.join(ROOT, "web", "img", "unit")
    os.makedirs(web_dir, exist_ok=True)
    credits_path = os.path.join(web_dir, "kredit.json")
    credits = json.load(open(credits_path, encoding="utf-8")) if os.path.exists(credits_path) else {}

    if not local_only:
        for uid, titles in UNIT.items():
            dest = os.path.join(web_dir, f"{uid}.jpg")
            if os.path.exists(dest) and "--force" not in sys.argv:
                print(f"-- {uid}: sudah ada (pakai --force untuk unduh ulang)")
                continue
            src, file_name = find_photo(titles)
            if not src:
                print(f"!! {uid}: foto tidak ditemukan — taruh foto sendiri di web/img/unit/{uid}.jpg")
                continue
            try:
                open(dest, "wb").write(get(src, raw=True))
            except Exception as e:
                print(f"!! {uid}: gagal unduh ({e})")
                continue
            credits[uid] = credit_of(file_name)
            print(f"ok {uid}: {file_name}")
            time.sleep(0.4)
        json.dump(credits, open(credits_path, "w", encoding="utf-8"), ensure_ascii=False, indent=1)

    # ---- pasang ke web ----
    mapping = {}
    for uid in UNIT:
        f = os.path.join(web_dir, f"{uid}.jpg")
        if not os.path.exists(f):
            continue
        if embed:
            src = "data:image/jpeg;base64," + base64.b64encode(open(f, "rb").read()).decode()
        else:
            src = f"img/unit/{uid}.jpg?v={int(os.path.getmtime(f))}"
        mapping[uid] = {"src": src, "credit": credits.get(uid, "Foto armada PT 107")}
    patch_index(mapping)

    # ---- API, database, Flutter ----
    api_dir = os.path.join(ROOT, "api", "uploads", "units")
    app_dir = os.path.join(ROOT, "mobile", "assets", "units")
    os.makedirs(api_dir, exist_ok=True)
    os.makedirs(app_dir, exist_ok=True)
    sql = ["-- Foto unit (digenerate ambil-foto.py). Import setelah seed.sql.", "SET NAMES utf8mb4;"]
    for uid in mapping:
        f = os.path.join(web_dir, f"{uid}.jpg")
        shutil.copy2(f, os.path.join(api_dir, f"{uid}.jpg"))
        shutil.copy2(f, os.path.join(app_dir, f"{uid}.jpg"))
        sql.append(f"UPDATE vehicles SET photo_url = 'units/{uid}.jpg', "
                   f"photo_credit = '{sql_escape(credits.get(uid, 'Foto armada PT 107'))}' WHERE code = '{uid}';")
    open(os.path.join(ROOT, "database", "foto_unit.sql"), "w", encoding="utf-8").write("\n".join(sql) + "\n")
    open(os.path.join(web_dir, "KREDIT.txt"), "w", encoding="utf-8").write(
        "\n".join(f"{k}: {v}" for k, v in credits.items()) + "\n")

    missing = [u for u in UNIT if u not in mapping]
    print(f"\nSelesai: {len(mapping)}/{len(UNIT)} foto terpasang" + (" (ditanam di index.html)" if embed else "") + ".")
    if missing:
        print("Belum ada foto:", ", ".join(missing), "-> taruh file sendiri lalu jalankan: python3 ambil-foto.py --lokal")
    print("Berikutnya: import database/foto_unit.sql di phpMyAdmin, upload ulang folder web/ dan api/uploads/.")


if __name__ == "__main__":
    main()
