#!/usr/bin/env python3
"""Filter monocle JSONL to rows carrying well-known BGP communities.

Usage:
    monocle search ... --format json-line | python3 filter_well_known.py > filtered.jsonl

The filter handles both numeric 65535:* output and monocle's symbolic names for
classic well-known communities, such as `no-export` and `no-advertise`.
"""

import json
import sys


NAME_TO_NUMERIC = {
    "no-export": "65535:65281",
    "no_advertise": "65535:65282",
    "no-advertise": "65535:65282",
    "no-export-subconfed": "65535:65283",
    "no_export_subconfed": "65535:65283",
    "nopeer": "65535:65284",
    "blackhole": "65535:666",
    "graceful-shutdown": "65535:0",
    "accept-own": "65535:1",
    "llgr-stale": "65535:6",
    "no-llgr": "65535:7",
}


def carries_well_known_community(record: dict) -> bool:
    """Return True if a monocle JSON record carries a well-known community."""
    communities = [str(community).lower() for community in (record.get("communities") or [])]
    return any(
        community.startswith("65535:") or community in NAME_TO_NUMERIC
        for community in communities
    )


def main() -> int:
    for line in sys.stdin:
        if not line.strip():
            continue

        try:
            record = json.loads(line)
        except json.JSONDecodeError:
            continue

        if carries_well_known_community(record):
            # Preserve original lines so downstream scripts can see exact monocle output.
            print(line, end="" if line.endswith("\n") else "\n")

    return 0


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