"""Read a LOCAL .pyi as text; never import or execute it. No connection to Resolve.
Presence is documentation evidence, not a live capability test. Missing names
refer only to this exact file, not every past or future Resolve release.
"""
import argparse
import ast
import hashlib
import json
from pathlib import Path

CHECKS = {
    "Timeline": ["GetTrackCount", "AddTrack", "GetTrackSubType", "SetTrackLock",
                 "GetIsTrackLocked", "DeleteClips", "SplitClip", "SplitClips", "TrimClip"],
    "TimelineItem": ["GetType", "GetLinkedItems", "GetStart", "GetEnd", "GetDuration",
                     "GetLeftOffset", "GetRightOffset", "SetStart", "SetEnd",
                     "SetLeftOffset", "SetRightOffset", "Split", "Trim"],
}


def audit(path):
    path = Path(path)
    if path.suffix.lower() != ".pyi":
        raise ValueError("Pass the installed DaVinciResolveScript.pyi, not a script or binary")
    if not path.is_file():
        raise ValueError("A regular local .pyi file is required")
    with path.open("rb") as stream:
        raw = stream.read(2 * 1024 * 1024 + 1)
    if len(raw) > 2 * 1024 * 1024:
        raise ValueError("File exceeds this tutorial's 2 MiB bound")
    tree = ast.parse(raw.decode("utf-8-sig"), filename=path.name)
    result = {}
    for name, wanted in CHECKS.items():
        classes = [n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == name]
        if len(classes) != 1:
            raise ValueError("Expected one top-level class: " + name)
        methods = {n.name: n for n in classes[0].body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
        result[name] = {key: {"documented_in_this_file": key in methods,
                             "line": methods[key].lineno if key in methods else None,
                             "parameters": [a.arg for a in methods[key].args.args] if key in methods else []}
                        for key in wanted}
    return {"schema": "videomontazher.resolve.local-contract-audit.v1",
            "file_name": path.name, "sha256": hashlib.sha256(raw).hexdigest(),
            "bytes": len(raw), "status": "document_only_not_live_verified", "classes": result}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--doc", type=Path, required=True)
    args = parser.parse_args()
    try:
        print(json.dumps(audit(args.doc), ensure_ascii=False, indent=2))
        return 0
    except Exception as exc:
        print(json.dumps({"status": "not_audited", "error": type(exc).__name__ + ": " + str(exc)}))
        return 2


if __name__ == "__main__":
    raise SystemExit(main())
