#!/usr/bin/env python3
"""
build the game data from art/ and config/ into game/assets/ and game/data/.

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

steps: sprites, tower levels, maps, masks, config, checks, previews. 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/ or config/ changes.

requires python 3.11 or later and pillow.
"""

import json
import math
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"
CONFIG = ROOT / "config"
ASSETS = ROOT / "game" / "assets"
DATA = ROOT / "game" / "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"

TOOLS = sorted((ROOT / "tools").glob("*.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"])
# empty part of an hp bar: a darkened copy (art.md)
BAR_DARKEN = 0.35
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

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):
    inputs = [ART / f"{n}.png" for n in SPRITES]
    outputs = [ASSETS / f"{n}.png" for n in SPRITES] + [ASSETS / "hpm_empty.png", ASSETS / "hpb_empty.png"]
    if not stale(inputs, outputs, force):
        print("sprites: up to date")
        return False
    ASSETS.mkdir(parents=True, exist_ok=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 ("hpm", "hpb"):
            images.darken(im, BAR_DARKEN).save(ASSETS / f"{n}_empty.png", optimize=True)
    print(f"sprites: wrote {len(SPRITES)} sprites and 2 empty bars")
    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 apply_corrections(m, routes, fix):
    """
    apply routes.toml corrections for map m to a list of route dicts.
    each route dict has points, and gets a fixed weight or None.
    """
    for r in routes:
        r["weight"] = None
    for spec in fix.get("route", []):
        pts = [tuple(p) for p in spec["points"]]
        if "replace" in spec:
            routes[spec["replace"]]["points"] = pts
            routes[spec["replace"]]["manual"] = True
        else:
            routes.append({"points": pts, "weight": None, "manual": True})
    for k, v in fix.get("weights", {}).items():
        routes[int(k)]["weight"] = float(v)
    drop = set(fix.get("drop", []))
    for i, r in enumerate(routes):
        r["number"] = i
    return [r for i, r in enumerate(routes) if i not in drop]


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"]
    routes_toml = CONFIG / "routes.toml"
    inputs = [ART / f"map{m}mask.png" for m in range(MAPS)] + [routes_toml]
    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["placement"] == placement:
        print("masks: up to date")
        return cached["maps"], False

    fixes = tomllib.loads(routes_toml.read_text()).get("map", {})
    out = []
    for m in range(MAPS):
        t0 = time.time()
        mask = masks.Mask(ART / f"map{m}mask.png")
        cols, rows, grid = masks.placement_grid(mask, placement)
        found = masks.extract_routes(mask, ROUTE_SMOOTH, ROUTE_TOLERANCE)
        routes = [{"points": pts, "manual": False} for pts in found["routes"]]
        routes = apply_corrections(m, routes, fixes.get(str(m), {}))
        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,
            "path_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({"placement": placement, "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),
                "weight": r["weight"],
            } 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 and config/routes.toml")
               + "window.MM = window.MM || {};\nMM.maps = [\n" + body + "\n];\n")


# 5. 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", "route_preference", "tower", "placement",
                "economy", "waves", "hearts", "coins", "controls", "art", "debug", "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 ("damage", "range"):
            v = need(tw, k, list, f"tower.{tid}")
            if len(v) != 5:
                raise ConfigError(f"tower.{tid}: {k} needs 5 levels, has {len(v)}")
        for k in ("cost", "attack_time", "projectile_speed"):
            need(tw, k, float, f"tower.{tid}")
        need(tw, "projectile", str, f"tower.{tid}")
        if "slow" in tw and len(tw["slow"]) != 5:
            raise ConfigError(f"tower.{tid}: slow needs 5 levels")
    for k in ("footprint_radius", "max_gap", "min_tower_distance", "edge_distance",
              "snap_radius", "grid_cell"):
        need(cfg["placement"], k, float, "placement")
    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"):
            need(mp, k, float, where)
        need(mp, "monster_share", list, where)
        for w, wave in enumerate(mp.get("wave", []), start=1):
            for g, grp in enumerate(need(wave, "groups", list, f"{where} wave {w}"), start=1):
                gw = f"{where} wave {w} group {g}"
                mon = need(grp, "monster", str, gw)
                if mon not in cfg["monster"]:
                    raise ConfigError(f"{gw}: unknown monster {mon}")
                need(grp, "count", int, gw)
                for k in ("interval", "delay"):
                    if k in grp:
                        need(grp, k, float, gw)


def sprite_table():
    """name -> [width, height] of every image in game/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["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 game/data/config.js")


# 6. checks

def wave_totals(cfg, waves):
    """return per monster counts, regular coins, boss coins, regular hp."""
    counts = {}
    for wave in waves:
        for grp in wave["groups"]:
            counts[grp["monster"]] = counts.get(grp["monster"], 0) + grp["count"]
    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']}, path width {mp['path_width']:.0f},"
              f" {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 r in mp["routes"]:
            times = ", ".join(f"{r['length'] / s:.0f}" for s in speeds)
            fixed = f", weight {r['weight']}" if r["weight"] is not None else ""
            manual = ", manual" if r.get("manual") else ""
            print(f"  route {r['number']}: length {r['length']:.0f}, turning {r['turning']:.0f} deg,"
                  f" value {r['value']:.2f}{fixed}{manual}; 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)
        target = c["starting_coins"] * cfg["economy"]["coin_total_factor"]
        total = reg + boss
        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) * mons[k]["coins"] / reg if reg else 0 for k in regular]
        print("  coin share %: " + ", ".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 {total}, target {target:.0f};"
              f" regular hp {hp}")
        if abs(total - target) > cfg["economy"]["coin_tolerance"] * target:
            warn(f"map{m}: coins {total} are more than"
                 f" {cfg['economy']['coin_tolerance'] * 100:.0f} % off the target {target:.0f}")
        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))

        last = waves[-1]["groups"]
        bosses = [g["monster"] for w in waves for g in w["groups"] if mons[g["monster"]].get("boss")]
        if bosses != [f"b{m}"] or not mons[last[-1]["monster"]].get("boss") or last[-1]["count"] != 1:
            warn(f"map{m}: expected one b{m} as the last group of 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)}")


# 7. previews

def step_previews(maps, force, changed):
    outputs = [PREVIEW / f"map{m}.png" for m in range(MAPS)] + [PREVIEW / "towers.png"]
    if not changed and not stale([], 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).save(PREVIEW / "towers.png")
    print(f"previews: wrote {PREVIEW.relative_to(ROOT)}/")


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_config(cfg, force, changed)
    step_checks(cfg, maps)
    step_previews(maps, force, changed or masks_changed)
    print(f"\n{len(warnings)} warning(s)")
    return True


def watch():
    def snapshot():
        files = list(ART.iterdir()) + list(CONFIG.iterdir()) + 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())
