"""Curve check: how many of the moves in an animation file share one curve or one duration.

    python3 curvecheck.py yourfile.html [more files]

It reads the source of a GSAP animation (HTML or JS), finds every .to, .from and .fromTo call, works out the
curve (ease) and duration each one uses, and fails the file when one curve or one duration does most of the work:

  1. One curve on more than half of the moves fails.
  2. One duration on more than 60 % of the moves fails.
  3. Fewer than three different curves fails, once a file has six moves or more.

A move with no ease set anywhere counts as GSAP's default, power1.out, and a timeline's defaults are applied.
Fewer than six moves is too few to judge, and passes with a note. A value it cannot read (a function, a computed
value) is reported as unreadable, never guessed. It reads the source as text, so it can miss calls a helper
builds at run time. Exit code 1 when any file fails.

Written by EKB Labs for our own files, where it fails 10 of 47. Plain Python 3, standard library only.
"""
import re, sys
from collections import Counter

TOP_EASE, TOP_DURATION, MIN_TWEENS, MIN_EASES = 0.5, 0.6, 6, 3
GSAP_DEFAULT = ("power1.out", "0.5")  # what GSAP uses when a timeline sets no defaults


def call_args(text, start):
    """The text of one call's arguments, from just after its "(" to the matching ")"."""
    depth = 1
    for i in range(start, min(len(text), start + 4000)):
        depth += (text[i] in "([{") - (text[i] in ")]}")
        if depth == 0: return text[start:i]
    return text[start:start + 600]


def read(chunk, key, consts, default, objs=None, args=None):
    """A tween's ease or duration: a literal, a number, a constant we can resolve, or "?name" when it cannot be read.
    A value set through a spread object (`{ ...CLEAR, y: 0 }`) is read from that object's definition."""
    m = re.search(r"\b%s\s*:\s*(?:[\"']([^\"']+)[\"']|([0-9.]+)|([A-Za-z_$][\w$.]*))" % key, chunk)
    if m:
        lit, num, name = m.groups()
        kit = re.fullmatch(r"(?:K|EKBMotion)\.EASE\.(\w+)", name or "")
        if kit: return "kit:" + kit.group(1)
        return lit if lit is not None else "%g" % float(num) if num is not None else consts.get(name, "?" + name)
    if re.search(r"[,{]\s*%s\s*[,}]" % key, chunk): return consts.get(key, "?" + key)   # shorthand { ease }
    for name in re.findall(r"\.\.\.\s*([A-Za-z_$][\w$.]*)", chunk if args is None else args):
        if name not in (objs or {}): return "?..." + name
        v = read(objs[name], key, consts, None, objs)
        if v is not None: return v
    return default


def lint(text):
    """Count the ease and duration of every tween in a composition's source.
    ponytail: regex over source, so helper functions and computed values show as "?name"; read the live timeline in headless Chrome if that bites."""
    consts = {n: (lit or "%g" % float(num)) for n, lit, num in
              re.findall(r"(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:[\"']([^\"']+)[\"']|([0-9.]+))\s*[;,\n]", text)}
    dflt = re.search(r"defaults\s*(?::|\()\s*\{([^}]*)\}", text)
    d_ease, d_dur = GSAP_DEFAULT
    if dflt: d_ease, d_dur = read(dflt.group(1), "ease", consts, d_ease), read(dflt.group(1), "duration", consts, d_dur)
    objs = dict(re.findall(r"(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*\{([^{}]*)\}", text))
    calls = list(re.finditer(r"(?<!Array)\.(?:to|from|fromTo)\(", text))
    eases, durs, defaulted = Counter(), Counter(), 0
    for n, m in enumerate(calls):
        chunk = text[m.end():calls[n + 1].start() if n + 1 < len(calls) else m.end() + 600]
        args = call_args(text, m.end())
        ease = read(chunk, "ease", consts, None, objs, args)
        if ease is None:   # nothing set on the tween: the timeline default, or GSAP's own
            ease = d_ease; defaulted += not (dflt and re.search(r"\bease\b", dflt.group(1)))
        eases[ease] += 1
        durs[read(chunk, "duration", consts, d_dur, objs, args)] += 1
    for m in re.finditer(r"\b(?:K|EKBMotion)\.(enter|exit|travel|emphasis|cut|hold)\(", text):   # the house kit, motion/kit
        eases["kit:" + m.group(1)] += 1; durs["?kit"] += 1
    n, reasons, fail = sum(eases.values()), [], False
    if n < MIN_TWEENS:
        reasons.append("too few moves to judge (%d)" % n)
    else:
        (te, ce), (td, cd) = eases.most_common(1)[0], durs.most_common(1)[0]
        unread = sum(c for k, c in eases.items() if k.startswith("?"))
        skip = ("?", "kit:")                         # a kit class repeats by design; its durations come from distance
        if unread: reasons.append("ease not readable on %d of %d moves" % (unread, n))
        if ce / n > TOP_EASE and not te.startswith(skip):
            fail = True; reasons.append("%s on %d of %d moves (%d%%)" % (te, ce, n, round(100 * ce / n)))
        if cd / n > TOP_DURATION and not td.startswith("?"):
            fail = True; reasons.append("duration %s s on %d of %d moves (%d%%)" % (td, cd, n, round(100 * cd / n)))
        if len(eases) < MIN_EASES and not unread:
            fail = True; reasons.append("only %d distinct eases" % len(eases))
    return dict(tweens=n, eases=dict(eases), durations=dict(durs), defaulted=defaulted, verdict="FAIL" if fail else "PASS", reasons=reasons)


def main(argv):
    if not argv:
        print(__doc__); return 2
    bad = 0
    for p in argv:
        r = lint(open(p, encoding="utf-8", errors="replace").read())
        bad += r["verdict"] == "FAIL"
        print("%s  %s  %d moves  %s" % (r["verdict"], p, r["tweens"], "; ".join(r["reasons"]) or "varied"))
        top = Counter(r["eases"]).most_common(3)
        if top: print("      curves: " + ", ".join("%s %d" % kv for kv in top))
    return 1 if bad else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
