#!/usr/bin/env python3
"""Export the latest completed zcrawl round as aggregate JSON."""
import argparse
import csv
import gzip
import fcntl
import ipaddress
import json
import os
import random
import re
import socket
import sqlite3
import statistics
import sys
import tempfile
import time
from collections import Counter
from contextlib import closing
from pathlib import Path

SCHEMA_VERSION = 2
IMPLEMENTATIONS = {"zebra", "zakura", "zcashd", "other", "unknown"}
FAILURES = {
    "connect_timeout", "connect_refused", "connect_unreachable", "connect_error",
    "handshake_timeout", "connection_closed", "connection_reset", "io_error",
    "bad_magic", "bad_command", "bad_checksum", "oversized_message",
    "malformed_message", "too_many_messages", "self_connection",
}
VERSION = re.compile(r"([0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4})(-.*)?")
SUFFIX = re.compile(r"-(modified|(rc|alpha|beta)(\.?[0-9]{1,3})?)")
COUNTRY = re.compile(r"[A-Z]{2}")
INT32_MAX = 2**31 - 1
UINT64_MAX = 2**64 - 1
DAY = 86400
HEIGHT_TOLERANCE = 100
NU7_HEIGHT = 3543405
NU7_PROTOCOL = 170190


class ExportError(Exception):
    pass


def safe_version(text):
    # Arbitrary user-agent suffixes can contain addresses or other operator data.
    match = VERSION.fullmatch(text) if isinstance(text, str) else None
    if not match:
        return "*" if text else ""
    base, suffix = match.group(1), match.group(2) or ""
    return base + (suffix if not suffix or SUFFIX.fullmatch(suffix) else "-*")


def implementation(text):
    return text if text in IMPLEMENTATIONS else "unknown"


def endpoint_ip(address):
    if not isinstance(address, str):
        return None
    if address.startswith("["):
        address = address[1:].partition("]")[0]
    elif address.count(":") == 1:
        address = address.partition(":")[0]
    try:
        return ipaddress.ip_address(address)
    except ValueError:
        return None


def endpoint_key(address, column_port, default_port):
    """Normalize SocketAddr strings and older IP-only observations."""
    ip = endpoint_ip(address)
    if ip is None:
        raise ExportError("invalid IP for a reached endpoint")
    if address.startswith("["):
        _, close, suffix = address.partition("]")
        if not close or (suffix and not suffix.startswith(":")):
            raise ExportError("invalid reached endpoint")
        port = suffix[1:] if suffix else column_port
    elif address.count(":") == 1:
        port = address.partition(":")[2]
    else:
        port = column_port
    try:
        port = default_port if port is None else int(port)
    except (TypeError, ValueError):
        raise ExportError("invalid port for a reached endpoint") from None
    if not 0 < port <= 65535:
        raise ExportError("invalid port for a reached endpoint")
    return ip, port


def synchronization(heights, reference):
    if not heights:
        return None
    behind = Counter(height for height in heights if height < reference - HEIGHT_TOLERANCE)
    behind_count = sum(behind.values())
    ahead = sum(height > reference + HEIGHT_TOLERANCE for height in heights)
    cluster = None
    if behind:
        height = min(behind, key=lambda h: (-behind[h], h))
        if behind[height] >= 3:
            cluster = {"height": height, "count": behind[height]}
    return {
        "reference": reference,
        "tolerance": HEIGHT_TOLERANCE,
        "near": len(heights) - behind_count - ahead,
        "behind": behind_count,
        "ahead": ahead,
        "largest_stall": cluster,
    }


def coordinates(lat, lon):
    try:
        lat, lon = float(lat), float(lon)
    except ValueError:
        return None
    if -90 <= lat <= 90 and -180 <= lon <= 180:
        return (round(lat, 1) or 0.0, round(lon, 1) or 0.0)
    return None


def match_ranges(path, nodes, columns):
    """Stream sorted IPv4/IPv6 ranges and yield only those with reached endpoints."""
    pending = {family: iter(sorted(peers, key=lambda peer: peer[0])) for family, peers in nodes.items()}
    wanted = {family: next(peers, None) for family, peers in pending.items()}
    previous_end = {}
    opener = gzip.open if path.suffix == ".gz" else open
    with opener(path, "rt", newline="", encoding="utf-8") as source:
        for row in csv.reader(source, strict=True):
            if not row:
                continue
            if len(row) != columns:
                raise ExportError(f"expected a {columns}-column DB-IP CSV without a header")
            start, end = row[:2]
            family = socket.AF_INET6 if ":" in start else socket.AF_INET
            try:
                low, high = (socket.inet_pton(family, address) for address in (start, end))
            except OSError:
                raise ExportError("invalid DB-IP IP range") from None
            if low > high or (family in previous_end and low <= previous_end[family]):
                raise ExportError("DB-IP ranges must be sorted and disjoint within each IP family")
            previous_end[family] = high
            peer = wanted[family]
            matches = []
            while peer is not None and peer[0] <= high:
                if peer[0] >= low:
                    matches.append(peer)
                peer = next(pending[family], None)
            wanted[family] = peer
            if matches:
                yield row, matches


def locate(path, nodes, reference):
    countries, points = Counter(), []
    for row, matches in match_ranges(path, nodes, 8):
        code = row[3]
        if not COUNTRY.fullmatch(code) or code == "ZZ":
            continue
        countries[code] += len(matches)
        point = coordinates(*row[6:])
        if point is None:
            continue
        for _, client, version, height in matches:
            state = "unknown"
            if wire_int(height, 0):
                state = ("behind" if height < reference - HEIGHT_TOLERANCE else
                         "ahead" if height > reference + HEIGHT_TOLERANCE else "near")
            points.append([*point, client, version, state, code])
    random.SystemRandom().shuffle(points)
    return countries, points


def hosting_summary(path, nodes):
    counts = Counter()
    for row, matches in match_ranges(path, nodes, 4):
        asn, name = row[2:]
        if not re.fullmatch(r"[0-9]{1,10}", asn) or not 0 < int(asn) <= 2**32 - 1:
            continue
        name = " ".join(name.split())[:160].strip()
        if name:
            counts[name] += len(matches)
    top = pairs(counts, 10)
    classified = sum(counts.values())
    other = classified - sum(entry["count"] for entry in top)
    return {
        "hosting": top + ([{"name": None, "count": other}] if other else []),
        "hosting_covered": classified,
        "hosting_top3": sum(entry["count"] for entry in top[:3]),
    }


def pairs(counter, limit):
    ordered = sorted(counter.items(), key=lambda item: (-item[1], item[0]))
    return [{"name": name, "count": count} for name, count in ordered[:limit]]


def wire_int(value, low):
    return type(value) is int and low <= value <= INT32_MAX


def service_mask(value):
    # SQLite INTEGER can store the wire mask as a signed 64-bit value.
    if isinstance(value, str):
        if re.fullmatch(r"0[xX][0-9a-fA-F]{1,16}", value):
            value = int(value, 16)
        elif re.fullmatch(r"-?[0-9]{1,20}", value):
            value = int(value, 10)
    if type(value) is int and -(2**63) <= value <= UINT64_MAX:
        return f"0x{value & UINT64_MAX:x}"
    return None


def read_snapshot(db, geo_path, now, interval_minutes, asn_path=None):
    software, versions, protocols, services = Counter(), Counter(), Counter(), Counter()
    families, failures = Counter(), Counter()
    releases = {"zebra": Counter(), "zakura": Counter()}
    nodes = {socket.AF_INET: [], socket.AF_INET6: []}
    heights = []
    with closing(sqlite3.connect(Path(db).resolve().as_uri() + "?mode=ro", uri=True, timeout=10)) as con:
        con.execute("BEGIN")
        version = con.execute("PRAGMA user_version").fetchone()[0]
        if version != SCHEMA_VERSION:
            raise ExportError(f"schema version {version}, expected {SCHEMA_VERSION}")
        network = con.execute("SELECT value FROM meta WHERE key='network'").fetchone()
        if not network or network[0] not in ("mainnet", "testnet"):
            raise ExportError("missing mainnet or testnet metadata")
        last = con.execute("""
            SELECT id, started_at, finished_at, nodes_reached, addresses_tried, hit_time_limit
            FROM rounds WHERE status='complete' ORDER BY started_at DESC, id DESC LIMIT 1
        """).fetchone()
        if not last:
            raise ExportError("no completed crawl round")
        if now is None:
            now = int(time.time())
        rid, started, finished, reached, tried, limit = last
        if any(type(n) is not int or n < 0 for n in (started, finished, reached, tried)):
            raise ExportError("invalid round totals")
        if finished < started or reached > tried:
            raise ExportError("inconsistent round totals")

        # Earlier local databases can lack the optional handshake detail columns.
        columns = {column[1] for column in con.execute("PRAGMA table_info(observations)")}
        detail = [name if name in columns else "NULL" for name in
                  ("protocol_version", "start_height", "services")]
        observations = con.execute(
            "SELECT address, reachable, failure_reason, implementation, version, "
            + ", ".join(detail) + " FROM observations WHERE round_id=?",
            (rid,),
        )
        history = con.execute("""
            SELECT finished_at, nodes_reached FROM (
                SELECT id, finished_at, nodes_reached FROM rounds WHERE status='complete'
                ORDER BY started_at DESC, id DESC LIMIT 168
            ) ORDER BY finished_at, id
        """).fetchall()
        first_completed_at = con.execute(
            "SELECT min(finished_at) FROM rounds WHERE status='complete'"
        ).fetchone()[0]
        port_column = "o.port" if "port" in columns else "NULL"
        default_port = 8233 if network[0] == "mainnet" else 18233
        reached_rows = con.execute(f"""
            SELECT DISTINCT o.address, {port_column}
            FROM rounds AS r JOIN observations AS o ON o.round_id = r.id
            WHERE r.status='complete' AND r.finished_at BETWEEN ? AND ? AND o.reachable
        """, (now - DAY, now))
        reached_24h = len({endpoint_key(address, port, default_port) for address, port in reached_rows})
        inbound = None
        if con.execute("SELECT EXISTS (SELECT 1 FROM inbound)").fetchone()[0]:
            inbound = con.execute("""
                SELECT count(DISTINCT address) FROM inbound
                WHERE handshake_complete=1 AND observed_at BETWEEN ? AND ?
            """, (now - DAY, now)).fetchone()[0]

        for address, reachable, failure, client, version, protocol, height, service in observations:
            if not reachable:
                failures[failure if failure in FAILURES else "other_error"] += 1
                continue
            client = implementation(client)
            software[client] += 1
            version = safe_version(version)
            versions[f"{client} {version}".strip()] += 1
            if client in releases and version:
                releases[client][version] += 1
            ip = endpoint_ip(address)
            if ip is not None:
                families[f"IPv{ip.version}"] += 1
                if geo_path is not None or asn_path is not None:
                    family = socket.AF_INET if ip.version == 4 else socket.AF_INET6
                    nodes[family].append((ip.packed, client, version, height))
            if wire_int(protocol, 1):
                protocols[str(protocol)] += 1
            if wire_int(height, 0):
                heights.append(height)
            mask = service_mask(service)
            if mask is not None:
                services[mask] += 1

    if sum(software.values()) > reached or sum(failures.values()) > tried - reached:
        raise ExportError("observation counts exceed the completed round totals")
    reference = statistics.median(heights) if heights else None
    countries, points = locate(geo_path, nodes, reference) if geo_path is not None else (Counter(), [])
    # Only fields reported by this round contribute to its NU7 counters.
    nu7 = {}
    if network[0] == "mainnet":
        if protocols:
            nu7["at_least"] = sum(n for value, n in protocols.items() if int(value) >= NU7_PROTOCOL)
            nu7["below"] = sum(protocols.values()) - nu7["at_least"]
        if heights:
            nu7["previous_block"] = heights.count(NU7_HEIGHT - 1)

    result = {
        "generated_at": now,
        "interval_minutes": interval_minutes,
        "network": network[0],
        "latest": {
            "started_at": started, "finished_at": finished, "nodes_reached": reached,
            "addresses_tried": tried, "hit_time_limit": bool(limit),
        },
        "first_completed_at": first_completed_at,
        "reached_24h": reached_24h,
        "inbound_24h": inbound,
        "history": [{"t": stamp, "reached": count} for stamp, count in history],
        "implementations": pairs(software, len(IMPLEMENTATIONS)),
        "versions": pairs(versions, 8),
        "protocols": {"reported": sum(protocols.values()), "values": pairs(protocols, 8)},
        "height": {
            "reported": len(heights), "min": min(heights), "max": max(heights),
            "median": reference,
        } if heights else None,
        "sync": synchronization(heights, reference),
        "services": {"reported": sum(services.values()), "values": pairs(services, 5)},
        "families": pairs(families, 2),
        "failures": pairs(failures, 5),
        "geolocation_enabled": geo_path is not None,
        "countries": [{"code": code, "count": count}
                      for code, count in sorted(countries.items(), key=lambda item: (-item[1], item[0]))],
        "points": points,
        "release_versions": {client: pairs(counts, len(counts)) for client, counts in releases.items()},
    }
    if nu7:
        result["nu7"] = nu7
    if asn_path is not None:
        result.update(hosting_summary(asn_path, nodes))
    return result


def publish(data, output, script):
    payload = json.dumps(data, separators=(",", ":"), allow_nan=False)
    staged = []
    try:
        for destination, contents in ((script, "window.ZDATA=" + payload + ";\n"), (output, payload + "\n")):
            with tempfile.NamedTemporaryFile(
                mode="w", encoding="utf-8", dir=destination.parent, prefix=".zcrawl-", delete=False
            ) as target:
                temporary = Path(target.name)
                staged.append((temporary, destination))
                target.write(contents)
            temporary.chmod(0o644)
        for temporary, destination in staged:
            os.replace(temporary, destination)
    finally:
        for temporary, _ in staged:
            temporary.unlink(missing_ok=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("db", type=Path)
    parser.add_argument("output", type=Path, help="JSON destination; .js is written alongside it")
    parser.add_argument("city_csv", type=Path, nargs="?", help="DB-IP City Lite CSV (plain or gzip)")
    parser.add_argument("--asn-csv", type=Path, help="sorted DB-IP ASN Lite CSV (plain or gzip)")
    parser.add_argument("--interval-minutes", type=int, required=True, help="configured crawl interval")
    args = parser.parse_intermixed_args()
    if not 0 < args.interval_minutes < 2**53:
        parser.error("--interval-minutes must be a positive integer below 2**53")
    try:
        script = args.output.with_suffix(".js")
        inputs = {path.resolve() for path in (args.db, args.city_csv, args.asn_csv) if path is not None}
        destinations = {args.output.resolve(), script.resolve()}
        if inputs & destinations or len(destinations) != 2:
            raise ExportError("both outputs must be separate from each other and from the input files")
        directory = os.open(args.output.parent, os.O_RDONLY)
        try:
            fcntl.flock(directory, fcntl.LOCK_EX)
            if args.output.is_dir() or script.is_dir():
                raise ExportError("the destinations must be file paths")
            data = read_snapshot(args.db, args.city_csv, None, args.interval_minutes, args.asn_csv)
            publish(data, args.output, script)
        finally:
            os.close(directory)
    except ExportError as error:
        print(f"export.py: {error}", file=sys.stderr)
        return 1
    except (OSError, sqlite3.Error, ValueError, csv.Error):
        print("export.py: could not read the input files or publish data", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
