#!/usr/bin/python3
"""Push live activities to the Moodtop Dynamic Island.

  mood-activity set <id> [key=value ...]        e.g. mood-activity set build title="Compiling" progress=0.4 icon=hammer
  mood-activity set <id> --json '{"title": ...}'
  mood-activity flash <id> <title> [sub] [--icon NAME] [--seconds N] [--color CSS]
  mood-activity clear <id>
  mood-activity list
Numbers and true/false are parsed; see moodactivity.py for every field.
"""
import json
import sys

sys.path.insert(0, "/usr/lib/mood/runtime")
import moodactivity  # noqa: E402


def val(v):
    if v in ("true", "false"):
        return v == "true"
    try:
        return float(v) if "." in v else int(v)
    except ValueError:
        return v


def main(a):
    if not a or a[0] in ("-h", "--help"):
        print(__doc__.strip())
        return 0
    cmd, rest = a[0], a[1:]
    if cmd == "list":
        print(json.dumps(moodactivity.read_all(), indent=1))
    elif cmd == "clear" and rest:
        moodactivity.clear(rest[0])
    elif cmd == "set" and rest:
        fields = {}
        if len(rest) > 2 and rest[1] == "--json":
            fields = json.loads(rest[2])
        else:
            for kv in rest[1:]:
                k, _, v = kv.partition("=")
                fields[k] = val(v)
        moodactivity.set(rest[0], **fields)
    elif cmd == "flash" and len(rest) >= 2:
        opts, pos, i = {}, [], 0
        while i < len(rest):
            if rest[i].startswith("--") and i + 1 < len(rest):
                opts[rest[i][2:]] = rest[i + 1]
                i += 2
            else:
                pos.append(rest[i])
                i += 1
        moodactivity.flash(pos[0], pos[1], pos[2] if len(pos) > 2 else "", icon=opts.get("icon", "sparkles"),
                           color=opts.get("color"), seconds=float(opts.get("seconds", 4)))
    else:
        print(__doc__.strip(), file=sys.stderr)
        return 2
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except ValueError as e:
        print(f"mood-activity: {e}", file=sys.stderr)
        sys.exit(2)
