"""LOG356 のサムネイル（LOG356_thumbnail.html）を作る。
試算のタブの写真6枚を白黒にして埋め込み、5つの現場の「ロボットが人を呼んだ回数」（標準の条件）を添える。
使い方: python3 make_thumbnail.py <タブの写真のフォルダ（p2m-site/public/site/sim）> <results_*.json のフォルダ> <出力の html>
"""
import base64
import io
import json
import sys
from pathlib import Path

from PIL import Image, ImageOps

IMG, RES, OUT = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])


def find(name, **kw):
    rs = json.load(open(RES / f"results_{name}.json", encoding="utf-8"))["rows"]
    hit = [r for r in rs if all(r[k] == v for k, v in kw.items())]
    assert len(hit) == 1, (name, kw, len(hit))
    return hit[0]


calls = {
    "hospital": find("hospital", scale="mid", robots=1, demand=1, floors="same", stop_rate=0.05, dispatch="now", busy=0.6, speed=0.9)["calls"],
    "cleaning": find("cleaning", facility="mall", staff=3, robots=2, share=0.7, eff=0.8, stuck_per_h=0.5, dock=False)["calls"],
    "hotel": find("hotel", scale="mid", front=2, robots=1, demand=1, link="system", stop_rate=0.05, multi=1)["calls"],
    "security": find("security", scale="mid", guards=2, robots=1, incidents=6, false_per_h=0.5, rmode="cont")["calls"],
    "outdoor": find("outdoor", scale="mid", robots=4, operators=1, orders=60, int_rate=0.2, watch=10)["calls"],
}
CARDS = [
    ("serving", "SERVING", "RESTAURANT", None, "LOG351"),
    ("hospital", "SPECIMENS", "HOSPITAL", calls["hospital"], "PER DAY"),
    ("cleaning", "FLOORS", "MALL", calls["cleaning"], "PER NIGHT"),
    ("hotel", "AMENITIES", "HOTEL", calls["hotel"], "PER DAY"),
    ("security", "PATROL", "OFFICE", calls["security"], "PER NIGHT"),
    ("outdoor", "SIDEWALK", "DELIVERY", calls["outdoor"], "PER DAY"),
]


def gray_uri(name):
    im = Image.open(IMG / f"{name}.jpg").convert("L")
    im = ImageOps.autocontrast(im, cutoff=1)
    # 墨色（#0d0d0d）から紙色（#f5f5f0）の間の色だけにする
    im = ImageOps.colorize(im, black=(13, 13, 13), white=(245, 245, 240))
    buf = io.BytesIO(); im.save(buf, "JPEG", quality=78)
    return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()


cards = "".join(
    f'<div class="card"><img src="{gray_uri(k)}" alt=""><div class="cap"><span class="t">{t}</span><span class="p">{p}</span></div>'
    + (f'<div class="n">{v:.1f}<small>CALLS {u}</small></div>' if v is not None else f'<div class="n dim">#1<small>{u}</small></div>')
    + "</div>"
    for k, t, p, v, u in CARDS)

html = f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>LOG356 thumbnail</title>
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap">
<style>
* {{ box-sizing: border-box; margin: 0; }}
html, body {{ background: #0d0d0d; }}
.thumb {{ container-type: size; width: 100%; max-width: 1920px; aspect-ratio: 16 / 9; margin: 0 auto; background: #0d0d0d; color: #f5f5f0;
  font-family: "IBM Plex Mono", monospace; position: relative; overflow: hidden; }}
.top {{ position: absolute; left: 4.5cqw; top: 6cqh; right: 4.5cqw; display: grid; gap: 1.6cqh; }}
.kick {{ font-size: 1.15cqw; letter-spacing: .22em; color: #9a9a94; }}
h1 {{ font-size: 5.6cqw; line-height: 1.02; font-weight: 700; letter-spacing: -.01em; }}
h1 span {{ display: inline-block; background: #f5f5f0; color: #0d0d0d; padding: 0 .18em; margin-top: .6cqh; }}
.sub {{ font-size: 1.15cqw; letter-spacing: .12em; color: #c9c9c2; }}
.row {{ position: absolute; left: 4.5cqw; right: 4.5cqw; bottom: 6cqh; display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 1.2cqw; }}
.card {{ display: grid; gap: .9cqh; opacity: 0; transform: translateY(2cqh); animation: up .6s ease forwards; }}
.card:nth-child(2) {{ animation-delay: .12s; }} .card:nth-child(3) {{ animation-delay: .24s; }} .card:nth-child(4) {{ animation-delay: .36s; }}
.card:nth-child(5) {{ animation-delay: .48s; }} .card:nth-child(6) {{ animation-delay: .6s; }}
@keyframes up {{ to {{ opacity: 1; transform: none; }} }}
.card img {{ width: 100%; aspect-ratio: 4 / 3; object-fit: cover; display: block; border: .15cqw solid #f5f5f0; }}
.cap {{ display: flex; justify-content: space-between; align-items: baseline; border-bottom: .12cqw solid #4a4a46; padding-bottom: .6cqh; }}
.cap .t {{ font-size: 1.05cqw; font-weight: 600; letter-spacing: .1em; }}
.cap .p {{ font-size: .8cqw; letter-spacing: .14em; color: #9a9a94; }}
.n {{ font-size: 3.4cqw; font-weight: 700; line-height: 1; font-variant-numeric: tabular-nums; display: grid; gap: .6cqh; }}
.n small {{ font-size: .78cqw; font-weight: 500; letter-spacing: .14em; color: #9a9a94; }}
.n.dim {{ color: #6a6a66; }}
.stripe {{ position: absolute; right: 4.5cqw; top: 6cqh; width: 22cqw; height: 18cqh;
  background: repeating-linear-gradient(135deg, #f5f5f0 0 .12cqw, transparent .12cqw .9cqw); opacity: .18; }}
@media (prefers-reduced-motion: reduce) {{ .card {{ animation: none; opacity: 1; transform: none; }} }}
</style></head><body>
<div class="thumb">
  <div class="stripe"></div>
  <div class="top">
    <div class="kick">SERVICE ROBOT SIMULATION · SIMPY · 5 MORE SITES</div>
    <h1>THE ROBOT<br><span>CALLS A HUMAN.</span></h1>
    <div class="sub">HOW MANY TIMES, PER SHIFT, AT DEFAULT SETTINGS</div>
  </div>
  <div class="row">{cards}</div>
</div>
</body></html>
"""
OUT.write_text(html, encoding="utf-8")
print(OUT, {k: round(v, 1) for k, v in calls.items()})
