#!/usr/bin/env python3
"""
build the runnable game into www/: the game data from art/ and config/ into
www/assets/ and www/data/, and a copy of the hand-written files in game/.

usage: python3 tools/build.py [--force] [--watch]

steps: sprites, tower levels, maps, masks, sounds, config, checks, previews,
game files. a step is skipped when all its outputs are newer than its inputs
and the build scripts; --force runs every step. --watch reruns the build
whenever a file in art/, art/sounds/, art/digits/, config/ or game/ changes.

requires python 3.11 or later and pillow.
"""

import base64
import json
import math
import re
import shutil
import sys
import time
import tomllib
from pathlib import Path

from PIL import Image

# keep tools/ free of __pycache__
sys.dont_write_bytecode = True

import images
import masks
import preview

ROOT = Path(__file__).resolve().parent.parent
ART = ROOT / "art"
SOUNDS = ART / "sounds"
DIGITS = ART / "digits"
CONFIG = ROOT / "config"
GAME = ROOT / "game"
WWW = ROOT / "www"
ASSETS = WWW / "assets"
DATA = WWW / "data"
TEMP = ROOT / "temp"
PREVIEW = TEMP / "preview"
# route data of the last mask step, read when the step is skipped
MAPS_CACHE = TEMP / "build" / "maps.json"

# build scripts; tools/balance.py only reads the build's output
TOOLS = sorted(p for p in (ROOT / "tools").glob("*.py") if p.name != "balance.py")
HEADER = "// generated by tools/build.py from {src}, do not edit\n"

SPRITES = (["m%d" % i for i in range(5)] + ["b%d" % i for i in range(4)]
           + ["t%d" % i for i in range(4)] + ["p%d" % i for i in range(4)]
           + ["c%d" % i for i in range(4)] + ["hpm", "hpb"]
           # icons, buttons and screens (art.md)
           + ["coin_icon", "heart", "monster_icon", "play_button", "pause_button",
              "speed_x1", "speed_x2", "speed_x4", "sound_on", "sound_off", "next_wave",
              "shop_bubble", "shop_bubble_dark", "shop_bubble_dark2", "tower_popup",
              "upgrade_button", "sell_button", "monster_death", "boss_death",
              "splash", "splash_play", "map_won", "map_won_button",
              "game_lost", "game_lost_button", "game_won", "game_won_button"])
# hp bar variants (art.md): the empty part is a darkened copy, the bar of a
# slowed monster has its colour set to this hue in degrees
BAR_DARKEN = 0.35
BAR_SLOW_HUE = 220
BARS = ["hpm", "hpb"]
BAR_VARIANTS = [f"{n}{v}" for n in BARS for v in ("_empty", "_slow", "_slow_empty")]
MAPS = 4
MAP_QUALITY = 88
# centre line smoothing: moving average half window, simplify tolerance
ROUTE_SMOOTH = 8
ROUTE_TOLERANCE = 0.8
# number of decimals of route points in maps.js
ROUTE_DECIMALS = 1
# per map settings used by the mask step
MASK_SETTINGS = ("path_half_width", "spawn_distance", "exit_distance")
# tower levels, and the tower settings given as [level 1, last level]
TOWER_LEVELS = 5
TOWER_BY_LEVEL = ("damage", "range", "cost", "slow")
# number of decimals of tower values filled in between non-whole ends
TOWER_DECIMALS = 3

warnings = []


def warn(msg):
    warnings.append(msg)
    print("  warning:", msg)


def stale(inputs, outputs, force):
    """true when an output is missing or older than an input or a build script."""
    if force:
        return True
    try:
        oldest = min(p.stat().st_mtime for p in outputs)
    except FileNotFoundError:
        return True
    newest = max(p.stat().st_mtime for p in list(inputs) + TOOLS)
    return newest > oldest


def write_text(path, text):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text)


# 1. sprites

def step_sprites(force):
    # digits cut by tools/cut_digits.py, written as digit_NAME_N
    digits = sorted(DIGITS.glob("*.png"))
    inputs = [ART / f"{n}.png" for n in SPRITES] + digits + [DIGITS]
    outputs = ([ASSETS / f"{n}.png" for n in SPRITES + BAR_VARIANTS]
               + [ASSETS / f"digit_{p.name}" for p in digits])
    if not stale(inputs, outputs, force):
        print("sprites: up to date")
        return False
    ASSETS.mkdir(parents=True, exist_ok=True)
    for p in ASSETS.glob("digit_*.png"):
        p.unlink()
    for p in digits:
        images.trim(Image.open(p).convert("RGBA")).save(ASSETS / f"digit_{p.name}", optimize=True)
    for n in SPRITES:
        im = images.trim(Image.open(ART / f"{n}.png").convert("RGBA"))
        im.save(ASSETS / f"{n}.png", optimize=True)
        if n in BARS:
            slow = images.recolour(im, BAR_SLOW_HUE)
            images.darken(im, BAR_DARKEN).save(ASSETS / f"{n}_empty.png", optimize=True)
            slow.save(ASSETS / f"{n}_slow.png", optimize=True)
            images.darken(slow, BAR_DARKEN).save(ASSETS / f"{n}_slow_empty.png", optimize=True)
    print(f"sprites: wrote {len(SPRITES)} sprites, {len(BAR_VARIANTS)} bar variants"
          f" and {len(digits)} digits")
    return True


# 2. tower levels

def step_towers(force):
    changed = False
    for t in range(4):
        src = ART / f"t{t}p.png"
        outputs = [ASSETS / f"t{t}_{lv}.png" for lv in range(2, 6)]
        if not stale([src], outputs, force):
            continue
        for lv, im in enumerate(images.tower_levels(src), start=2):
            im.save(ASSETS / f"t{t}_{lv}.png", optimize=True)
        changed = True
    print("towers:", "wrote levels 2-5" if changed else "up to date")
    return changed


# 3. maps

def step_maps(force):
    changed = False
    for m in range(MAPS):
        src, dst = ART / f"map{m}.png", ASSETS / f"map{m}.jpg"
        if stale([src], [dst], force):
            images.map_copy(src, dst, MAP_QUALITY)
            changed = True
    print("maps:", "wrote jpeg copies" if changed else "up to date")
    return changed


# 4. masks

def route_values(routes):
    """
    fill in length, turning and value of each route (balance.md, route
    preference): the average of length relative to the longest route and
    straightness relative to the straightest, that is the least turning.
    """
    for r in routes:
        r["length"] = masks.polyline_length(r["points"])
        r["turning"] = masks.turning(r["points"])
    longest = max(r["length"] for r in routes)
    least = min(r["turning"] for r in routes)
    for r in routes:
        straight = least / r["turning"] if r["turning"] else 1.0
        r["value"] = (r["length"] / longest + straight) / 2


def step_masks(cfg, force):
    placement = cfg["placement"]
    settings = {"placement": placement,
                "maps": [{k: cfg["map"][str(m)][k] for k in MASK_SETTINGS} for m in range(MAPS)]}
    inputs = [ART / f"map{m}mask.png" for m in range(MAPS)]
    outputs = [DATA / "maps.js", MAPS_CACHE]
    cached = None
    if MAPS_CACHE.exists():
        cached = json.loads(MAPS_CACHE.read_text())
    # the placement settings are part of the input, compared by value
    if not stale(inputs, outputs, force) and cached and cached.get("settings") == settings:
        print("masks: up to date")
        return cached["maps"], False

    out = []
    for m in range(MAPS):
        t0 = time.time()
        mc = settings["maps"][m]
        mask = masks.Mask(ART / f"map{m}mask.png")
        found = masks.extract_routes(mask, ROUTE_SMOOTH, ROUTE_TOLERANCE)
        spaces = [(found["spawns"], mc["spawn_distance"]),
                  (found["exit_points"], mc["exit_distance"])]
        cols, rows, grid = masks.placement_grid(mask, placement, found["centre"],
                                                mc["path_half_width"], spaces)
        routes = [{"points": pts} for pts in found["routes"]]
        route_values(routes)
        g = found["graph"]
        out.append({
            "name": f"map{m}",
            "width": mask.w,
            "height": mask.h,
            "cell": placement["grid_cell"],
            "cols": cols,
            "rows": rows,
            "grid": grid,
            "line_width": found["width"],
            "entrances": [b[:3] for b in found["entrances"]],
            "exits": [b[:3] for b in found["exits"]],
            "routes": routes,
            "graph": {
                "nodes": [list(p) for p in g.nodes.values()],
                "edges": [e[2] for e in g.edges.values()],
            },
        })
        print(f"masks: map{m} {len(routes)} route(s), {time.time() - t0:.1f} s")

    write_maps_js(out)
    MAPS_CACHE.parent.mkdir(parents=True, exist_ok=True)
    MAPS_CACHE.write_text(json.dumps({"settings": settings, "maps": out}))
    return out, True


def write_maps_js(maps):
    def rnd(v):
        return round(v, ROUTE_DECIMALS)

    js = []
    for mp in maps:
        js.append({
            "name": mp["name"],
            "image": f"assets/{mp['name']}.jpg",
            "width": mp["width"],
            "height": mp["height"],
            "cell": mp["cell"],
            "cols": mp["cols"],
            "rows": mp["rows"],
            "grid": mp["grid"],
            "entrances": [[rnd(v) for v in b] for b in mp["entrances"]],
            "exits": [[rnd(v) for v in b] for b in mp["exits"]],
            "routes": [{
                "points": [rnd(v) for p in r["points"] for v in p],
                "length": rnd(r["length"]),
                "turning": rnd(r["turning"]),
                "value": round(r["value"], 3),
            } for r in mp["routes"]],
        })
    body = ",\n".join(json.dumps(m, separators=(",", ":")) for m in js)
    write_text(DATA / "maps.js", HEADER.format(src="art/map*mask.png")
               + "window.MM = window.MM || {};\nMM.maps = [\n" + body + "\n];\n")


# 5. sounds

def step_sounds(cfg, force):
    """
    embed art/sounds/*.mp3 as base64 in www/data/sounds.js, grouped by
    event: NAME.mp3 or the variants NAME_1.mp3, NAME_2.mp3 and so on.
    """
    inputs = sorted(SOUNDS.glob("*.mp3"))
    dst = DATA / "sounds.js"
    if not stale(inputs, [dst], force):
        print("sounds: up to date")
        return
    events = {}
    for p in inputs:
        name = re.sub(r"_\d+$", "", p.stem)
        events.setdefault(name, []).append(base64.b64encode(p.read_bytes()).decode("ascii"))
    for name in events:
        if name not in cfg["sound"]["event"]:
            warn(f"sounds: {name} has no entry in [sound.event]")
    body = ",\n".join(f" {json.dumps(k)}: {json.dumps(v)}" for k, v in events.items())
    write_text(dst, HEADER.format(src="art/sounds/")
               + "window.MM = window.MM || {};\nMM.sounds = {\n" + body + "\n};\n")
    size = dst.stat().st_size / 1024
    print(f"sounds: wrote {len(inputs)} sounds for {len(events)} events, {size:.0f} KB")


# 6. config

class ConfigError(Exception):
    pass


def need(table, key, kind, where):
    if key not in table:
        raise ConfigError(f"{where}: {key} missing")
    v = table[key]
    if kind is float:
        ok = isinstance(v, (int, float)) and not isinstance(v, bool)
    else:
        ok = isinstance(v, kind)
    if not ok:
        raise ConfigError(f"{where}: {key} should be {kind.__name__}, is {v!r}")
    return v


def check_config(cfg):
    """raise ConfigError on missing or malformed settings."""
    for sec in ("scale", "monster", "animation", "movement", "route_preference", "tower",
                "placement", "waves", "hearts", "coins", "controls", "art", "debug",
                "sound", "map"):
        if sec not in cfg:
            raise ConfigError(f"section [{sec}] missing")
    for mid, mon in cfg["monster"].items():
        for k in ("hp", "coins", "speed"):
            need(mon, k, float, f"monster.{mid}")
    for tid, tw in cfg["tower"].items():
        for k in TOWER_BY_LEVEL:
            if k == "slow" and k not in tw:
                continue
            v = need(tw, k, list, f"tower.{tid}")
            if len(v) != 2 or not all(isinstance(x, (int, float)) and not isinstance(x, bool)
                                      for x in v):
                raise ConfigError(f"tower.{tid}: {k} should be [level 1, level "
                                  f"{TOWER_LEVELS}], is {v!r}")
        for k in ("attack_time", "projectile_speed"):
            need(tw, k, float, f"tower.{tid}")
        need(tw, "projectile", str, f"tower.{tid}")
    for k in ("speed_variation", "offset", "lean", "wander_step", "fade_in"):
        need(cfg["movement"], k, float, "movement")
    for k in ("footprint_radius", "max_gap", "min_tower_distance", "edge_distance",
              "snap_radius", "grid_cell"):
        need(cfg["placement"], k, float, "placement")
    snd = cfg["sound"]
    need(snd, "enabled", bool, "sound")
    need(snd, "volume", float, "sound")
    need(snd, "beep_wave", str, "sound")
    for name, ev in need(snd, "event", dict, "sound").items():
        where = f"sound.event.{name}"
        need(ev, "volume", float, where)
        if "min_interval" in ev:
            need(ev, "min_interval", float, where)
        for note in ev.get("beep", []):
            if not (isinstance(note, list) and len(note) == 2):
                raise ConfigError(f"{where}: beep notes should be [frequency, seconds]")
    for m in range(MAPS):
        mp = cfg["map"].get(str(m))
        if mp is None:
            raise ConfigError(f"[map.{m}] missing")
        where = f"map.{m}"
        for k in ("starting_coins", "early_bonus", "wave_count") + MASK_SETTINGS:
            need(mp, k, float, where)
        for k, n in (("monster_share", 5), ("wave_size", 2), ("first_wave", 5)):
            v = need(mp, k, list, where)
            if len(v) != n or not all(isinstance(x, int) and not isinstance(x, bool) for x in v):
                raise ConfigError(f"{where}: {k} should be {n} whole numbers, is {v!r}")
        if "spawn_interval" in mp:
            need(mp, "spawn_interval", float, where)
        for w, wave in enumerate(mp.get("wave", []), start=1):
            ww = f"{where} wave {w}"
            for mon in need(wave, "monsters", dict, ww):
                if mon not in cfg["monster"]:
                    raise ConfigError(f"{ww}: unknown monster {mon}")
                need(wave["monsters"], mon, int, ww)


def tower_levels(ends):
    """
    the values for all tower levels from [level 1, last level], in equal
    steps. whole numbers when both ends are whole (halves round up),
    otherwise rounded to TOWER_DECIMALS.
    """
    first, last = ends
    whole = isinstance(first, int) and isinstance(last, int)
    out = []
    for i in range(TOWER_LEVELS):
        v = first + (last - first) * i / (TOWER_LEVELS - 1)
        out.append(math.floor(v + 0.5) if whole else round(v, TOWER_DECIMALS))
    return out


def sprite_table():
    """name -> [width, height] of every image in www/assets/ except maps."""
    out = {}
    for p in sorted(ASSETS.glob("*.png")):
        with Image.open(p) as im:
            out[p.stem] = list(im.size)
    return out


def step_config(cfg, force, assets_changed):
    src = CONFIG / "game.toml"
    dst = DATA / "config.js"
    if not stale([src], [dst], force) and not assets_changed:
        print("config: up to date")
        return
    out = {k: v for k, v in cfg.items() if k != "map"}
    out["tower"] = {tid: {k: tower_levels(v) if k in TOWER_BY_LEVEL else v
                          for k, v in tw.items()}
                    for tid, tw in cfg["tower"].items()}
    out["maps"] = []
    for m in range(MAPS):
        mp = dict(cfg["map"][str(m)])
        mp["waves"] = mp.pop("wave", [])
        out["maps"].append(mp)
    out["sprites"] = sprite_table()
    write_text(dst, HEADER.format(src="config/game.toml")
               + "window.MM = window.MM || {};\nMM.config = "
               + json.dumps(out, indent=1) + ";\n")
    print("config: wrote www/data/config.js")


# 7. checks

def wave_totals(cfg, waves):
    """return per monster counts, regular coins, boss coins, regular hp."""
    counts = {}
    for wave in waves:
        for mon, n in wave["monsters"].items():
            counts[mon] = counts.get(mon, 0) + n
    mons = cfg["monster"]
    reg = sum(n * mons[k]["coins"] for k, n in counts.items() if not mons[k].get("boss"))
    boss = sum(n * mons[k]["coins"] for k, n in counts.items() if mons[k].get("boss"))
    hp = sum(n * mons[k]["hp"] for k, n in counts.items() if not mons[k].get("boss"))
    return counts, reg, boss, hp


def step_checks(cfg, maps):
    print("\nchecks")
    mons = cfg["monster"]
    regular = sorted(k for k, v in mons.items() if not v.get("boss"))
    speeds = sorted({v["speed"] for v in mons.values()})
    for m, mp in enumerate(maps):
        c = cfg["map"][str(m)]
        print(f"\nmap{m}: {mp['width']}x{mp['height']}, line width {mp['line_width']:.0f},"
              f" road half width {c['path_half_width']}, {mp['grid'].count('1')} placement cells")
        if len(mp["entrances"]) == 0 or len(mp["exits"]) == 0:
            warn(f"map{m}: no entrance or no exit found")
        if not mp["routes"]:
            warn(f"map{m}: no routes")
        for k, r in enumerate(mp["routes"]):
            times = ", ".join(f"{r['length'] / s:.0f}" for s in speeds)
            print(f"  route {k}: length {r['length']:.0f}, turning {r['turning']:.0f} deg,"
                  f" value {r['value']:.2f}; walk time {times} s"
                  f" at speed {', '.join(str(s) for s in speeds)}")

        waves = c.get("wave", [])
        if len(waves) != c["wave_count"]:
            warn(f"map{m}: {len(waves)} waves, wave_count says {c['wave_count']}")
        if not waves:
            continue
        counts, reg, boss, hp = wave_totals(cfg, waves)
        n_reg = sum(counts.get(k, 0) for k in regular)
        print("  monsters: " + ", ".join(f"{k} {counts.get(k, 0)}" for k in sorted(counts))
              + f", {sum(counts.values())} in all")
        share = [100 * counts.get(k, 0) / n_reg if n_reg else 0 for k in regular]
        print("  share by count %: " + ", ".join(f"{k} {s:.0f} ({t})" for k, s, t
                                                 in zip(regular, share, c["monster_share"])))
        print(f"  coins: regular {reg}, boss {boss}, total {reg + boss},"
              f" {reg + boss + c['starting_coins']} with the starting coins;"
              f" regular hp {hp}, {reg / hp if hp else 0:.2f} coins per hp")
        per_wave = []
        for w, wave in enumerate(waves, start=1):
            _, r, b, _ = wave_totals(cfg, [wave])
            per_wave.append(r + b)
        print("  coins per wave: " + ", ".join(str(v) for v in per_wave))

        bosses = [(k, n) for w in waves for k, n in w["monsters"].items()
                  if n and mons[k].get("boss")]
        if bosses != [(f"b{m}", 1)] or not waves[-1]["monsters"].get(f"b{m}"):
            warn(f"map{m}: expected one b{m} in the last wave")
        bonus = c["early_bonus"] * (cfg["waves"]["first_break"]
                                    + cfg["waves"]["break"] * (len(waves) - 1))
        print(f"  early start bonus if every break is skipped: {math.floor(bonus)}")


# 8. previews

def step_previews(cfg, maps, force, changed):
    outputs = [PREVIEW / f"map{m}.png" for m in range(MAPS)] + [PREVIEW / "towers.png"]
    # the tower sheet shows the angles, pivots, footprint and sprite scale from game.toml
    if not changed and not stale([CONFIG / "game.toml"], outputs, force):
        print("previews: up to date")
        return
    PREVIEW.mkdir(parents=True, exist_ok=True)
    for m, mp in enumerate(maps):
        preview.map_preview(ART / f"map{m}.png", mp).save(PREVIEW / f"map{m}.png")
        if len(mp["routes"]) > 1:
            preview.route_sheet(ART / f"map{m}.png", mp).save(PREVIEW / f"map{m}_routes.png")
    preview.tower_sheet(ASSETS, cfg["art"]["angle"], cfg["art"]["pivot"],
                        cfg["placement"]["footprint_radius"],
                        cfg["scale"]["sprite"]).save(PREVIEW / "towers.png")
    print(f"previews: wrote {PREVIEW.relative_to(ROOT)}/")


# 9. game files

def game_files():
    """the hand-written files in game/, as paths relative to it."""
    return sorted(p.relative_to(GAME) for p in GAME.rglob("*")
                  if p.is_file() and p.name != ".DS_Store")


def step_game(force):
    """
    copy the files in game/ to www/ when they differ in time or size, and
    remove files from www/ that are no longer in game/. www/assets/ and
    www/data/ are left alone, as the other steps write them.
    """
    files = game_files()
    copied = 0
    for rel in files:
        src, dst = GAME / rel, WWW / rel
        a = src.stat()
        if not force and dst.exists():
            b = dst.stat()
            if b.st_mtime == a.st_mtime and b.st_size == a.st_size:
                continue
        dst.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(src, dst)
        copied += 1
    keep = set(files)
    removed = 0
    for p in sorted(WWW.rglob("*"), reverse=True):
        rel = p.relative_to(WWW)
        if rel.parts[0] in (ASSETS.name, DATA.name) or rel in keep:
            continue
        if p.is_file():
            p.unlink()
            removed += 1
        elif not any(p.iterdir()):
            p.rmdir()
    if copied or removed:
        print(f"game files: copied {copied}, removed {removed}")
    else:
        print("game files: up to date")


def build(force):
    warnings.clear()
    try:
        cfg = tomllib.loads((CONFIG / "game.toml").read_text())
        check_config(cfg)
    except (tomllib.TOMLDecodeError, ConfigError) as e:
        print("config error:", e)
        return False
    changed = step_sprites(force)
    changed |= step_towers(force)
    step_maps(force)
    maps, masks_changed = step_masks(cfg, force)
    step_sounds(cfg, force)
    step_config(cfg, force, changed)
    step_checks(cfg, maps)
    step_previews(cfg, maps, force, changed or masks_changed)
    step_game(force)
    print(f"\n{len(warnings)} warning(s)")
    return True


def watch():
    def snapshot():
        files = (list(ART.iterdir()) + list(SOUNDS.glob("*.mp3")) + list(DIGITS.glob("*.png"))
                 + list(CONFIG.iterdir()) + [GAME / p for p in game_files()] + TOOLS)
        return {p: p.stat().st_mtime for p in files if p.is_file()}

    seen = None
    while True:
        now = snapshot()
        if now != seen:
            seen = now
            print(time.strftime("\n== build %H:%M:%S"))
            try:
                build(False)
            except Exception as e:  # keep watching after a failed build
                print("build failed:", e)
        time.sleep(1)


def main():
    args = sys.argv[1:]
    if "--watch" in args:
        # show each line at once, also when the output goes to a file
        sys.stdout.reconfigure(line_buffering=True)
        try:
            watch()
        except KeyboardInterrupt:
            pass
        return 0
    return 0 if build("--force" in args) else 1


if __name__ == "__main__":
    sys.exit(main())
