#!/usr/bin/env python
# Copyright 2025 NetBox Labs Inc
"""CLI helper to ingest dry-run JSON messages into Diode."""

import argparse
import sys

from netboxlabs.diode.sdk import DiodeClient, load_dryrun_entities


def main() -> None:
    """Ingest JSON files generated by ``DiodeDryRunClient``."""
    parser = argparse.ArgumentParser(
        description="Load dry-run JSON messages and ingest them into Diode"
    )
    parser.add_argument(
        "-t",
        "--target",
        required=True,
        help="gRPC target of the Diode server, e.g. grpc://localhost:8080/diode",
    )
    parser.add_argument(
        "-a",
        "--app-name",
        required=True,
        help="Application name used when ingesting the dry-run messages",
    )
    parser.add_argument(
        "-v",
        "--app-version",
        required=True,
        help="Application version used when ingesting the dry-run messages",
    )
    parser.add_argument(
        "-c",
        "--client-id",
        help="OAuth2 client ID. Defaults to the DIODE_CLIENT_ID environment variable if not provided",
    )
    parser.add_argument(
        "-k",
        "--client-secret",
        help="OAuth2 client secret. Defaults to the DIODE_CLIENT_SECRET environment variable if not provided",
    )
    parser.add_argument(
        "files",
        nargs="+",
        metavar="FILE",
        help="Dry-run JSON files to ingest",
    )

    args = parser.parse_args()

    with DiodeClient(
        target=args.target,
        app_name=args.app_name,
        app_version=args.app_version,
        client_id=args.client_id,
        client_secret=args.client_secret,
    ) as client:
        has_errors = False
        for file_path in args.files:
            entities = list(load_dryrun_entities(file_path))
            if entities:
                response = client.ingest(entities=entities)
                if response.errors:
                    print(f"Errors while ingesting {file_path}: {response.errors}", file=sys.stderr)
                    has_errors = True
                else:
                    print(f"Ingested {len(entities)} entities from {file_path}")
        if has_errors:
            sys.exit(1)


if __name__ == "__main__":
    main()
