#!/usr/bin/env python3
"""Example CINVAR plugin tool.

Contract (see docs/PLUGIN_GUIDE.md):
  * stdin  : the tool arguments as one JSON object
  * cwd    : the project root
  * stdout : the result (JSON recommended)
  * exit   : 0 = success; non-zero = error (stderr becomes the error message)
"""
import json
import sys


def main():
    try:
        args = json.load(sys.stdin) if not sys.stdin.isatty() else {}
    except json.JSONDecodeError as exc:
        print(f"arguments are not valid JSON: {exc}", file=sys.stderr)
        return 2
    try:
        with open("project.json", encoding="utf-8") as fh:
            project = json.load(fh)
    except OSError as exc:
        print(f"cannot read project.json: {exc}", file=sys.stderr)
        return 1
    timelines = project.get("timelines") or []
    tracks = [t for tl in timelines for t in (tl.get("tracks") or [])]
    clips = [c for t in tracks for c in (t.get("clips") or [])]
    out = {
        "project": project.get("name"),
        "revision": project.get("revision"),
        "assets": len(project.get("assets") or []),
        "timelines": len(timelines),
        "tracks": len(tracks),
        "clips": len(clips),
    }
    if args.get("include_asset_names"):
        out["asset_names"] = [a.get("name") for a in project.get("assets") or []]
    json.dump(out, sys.stdout)
    return 0


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