#!/usr/bin/env python3

import json
import sys
from pathlib import Path


def main() -> int:
    if len(sys.argv) != 2:
        print("Usage: count_keys.py <json-file>", file=sys.stderr)
        return 1

    path = Path(sys.argv[1])
    if not path.exists() or not path.is_file():
        print(f"File does not exist: {path}", file=sys.stderr)
        return 1

    try:
        text = path.read_text(encoding="utf-8")
    except OSError as exc:
        print(f"Failed to read file: {exc}", file=sys.stderr)
        return 1

    try:
        data = json.loads(text)
    except json.JSONDecodeError as exc:
        print(f"Invalid JSON: {exc}", file=sys.stderr)
        return 1

    if not isinstance(data, dict):
        print("Top-level JSON value must be an object", file=sys.stderr)
        return 1

    print(len(data))
    return 0


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