#!/usr/bin/env python3
"""MIT licensed; copyright 2026 Mohamed Jarray / Search Engine Trends.

Compare one observed source IP with a locally downloaded official prefix file.
This script makes no requests and changes no firewall rules.

MIT License

Copyright (c) 2026 Mohamed Jarray / Search Engine Trends

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

"""
import argparse
import ipaddress
import json


def matches_prefixes(address, document):
    ip = ipaddress.ip_address(address)
    prefixes = document.get("prefixes")
    if not isinstance(prefixes, list) or not prefixes:
        raise ValueError("Expected a non-empty official prefixes list")
    networks = []
    for item in prefixes:
        if not isinstance(item, dict):
            raise ValueError("Invalid prefix record")
        value = item.get("ipv4Prefix") or item.get("ipv6Prefix")
        if not value:
            raise ValueError("Missing ipv4Prefix or ipv6Prefix")
        networks.append(ipaddress.ip_network(value))
    return any(ip.version == network.version and ip in network for network in networks)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("prefix_file", help="Locally downloaded official JSON")
    parser.add_argument("source_ip", help="Observed request IP from a trusted log")
    args = parser.parse_args()
    try:
        with open(args.prefix_file, encoding="utf-8") as stream:
            document = json.load(stream)
        if not isinstance(document, dict):
            raise ValueError("Expected a JSON object")
        match = matches_prefixes(args.source_ip, document)
    except (OSError, ValueError, TypeError) as error:
        parser.exit(2, f"Verification unavailable: {error}\n")
    print("PREFIX_MATCH" if match else "NO_PREFIX_MATCH")
    print("IP ownership only; this does not prove crawling, indexing or citation.")
    return 0 if match else 1


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