
#!/usr/bin/env python3

import os
import sys
import osmium


if len(sys.argv) != 3:
    print(
        f"Usage: {sys.argv[0]} INPUT OUTPUT",
        file=sys.stderr,
    )
    sys.exit(1)


INPUT = sys.argv[1]
OUTPUT = sys.argv[2]


# ============================================================
# Tags réellement nécessaires à NextLimit
# ============================================================

WAY_TAGS = {

    # --------------------------------------------------------
    # Classification
    # --------------------------------------------------------

    "highway",

    # --------------------------------------------------------
    # Limitations de vitesse
    # --------------------------------------------------------

    "maxspeed",

    "maxspeed:forward",
    "maxspeed:backward",

    "maxspeed:conditional",

    "maxspeed:type",

    "source:maxspeed",

    "zone:maxspeed",

    # --------------------------------------------------------
    # Direction / graphe
    # --------------------------------------------------------

    "oneway",

    "junction",

    # --------------------------------------------------------
    # Restrictions d'accès
    # --------------------------------------------------------

    "access",

    "vehicle",

    "motor_vehicle",

    "motorcar",

    # --------------------------------------------------------
    # Service roads
    # --------------------------------------------------------

    "service",

    # --------------------------------------------------------
    # Informations utiles au debug / map matching
    #
    # On pourra éventuellement les enlever plus tard
    # pour gagner encore de la place.
    # --------------------------------------------------------

    "ref",

    "name",
}


WAY_PREFIXES = (

    "maxspeed:",

)


RELATION_TAGS = {

    "type",

    "restriction",

    "restriction:conditional",

    "except",
}


RELATION_PREFIXES = (

    "restriction:",

)


# ============================================================
# Utilitaires
# ============================================================

def filter_tags(tags, allowed, prefixes=()):

    result = {}

    for tag in tags:

        key = tag.k
        value = tag.v

        if key in allowed:
            result[key] = value
            continue

        if any(
            key.startswith(prefix)
            for prefix in prefixes
        ):
            result[key] = value

    return result


# ============================================================
# Handler
# ============================================================

class NextLimitHandler(osmium.SimpleHandler):

    def __init__(self, writer):

        super().__init__()

        self.writer = writer

        self.nodes = 0
        self.ways = 0
        self.relations = 0

        self.kept_tags = 0
        self.removed_tags = 0


    # --------------------------------------------------------
    # NODE
    #
    # Les nodes sont nécessaires à la géométrie des ways.
    #
    # Par contre leurs tags ne sont pas nécessaires pour
    # NextLimit à ce stade.
    # --------------------------------------------------------

    def node(self, node):

        self.nodes += 1

        original = len(node.tags)

        self.removed_tags += original

        if original:

            node = node.replace(tags={})

        self.writer.add_node(node)


    # --------------------------------------------------------
    # WAY
    # --------------------------------------------------------

    def way(self, way):

        self.ways += 1

        tags = filter_tags(
            way.tags,
            WAY_TAGS,
            WAY_PREFIXES,
        )

        original = len(way.tags)

        self.kept_tags += len(tags)

        self.removed_tags += (
            original - len(tags)
        )

        self.writer.add_way(
            way.replace(tags=tags)
        )


    # --------------------------------------------------------
    # RELATION
    # --------------------------------------------------------

    def relation(self, relation):

        self.relations += 1

        tags = filter_tags(
            relation.tags,
            RELATION_TAGS,
            RELATION_PREFIXES,
        )

        original = len(relation.tags)

        self.kept_tags += len(tags)

        self.removed_tags += (
            original - len(tags)
        )

        self.writer.add_relation(
            relation.replace(tags=tags)
        )


# ============================================================
# Traitement
# ============================================================

if os.path.exists(OUTPUT):
    os.unlink(OUTPUT)


writer = osmium.SimpleWriter(OUTPUT)

handler = NextLimitHandler(writer)

try:

    handler.apply_file(
        INPUT,
        locations=False,
    )

finally:

    writer.close()


# ============================================================
# Statistiques
# ============================================================

print()

print(
    "============================================================"
)

print(
    "           STATISTIQUES NEXTLIMIT"
)

print(
    "============================================================"
)

print()

print(
    f"Nodes       : {handler.nodes:,}"
)

print(
    f"Ways        : {handler.ways:,}"
)

print(
    f"Relations   : {handler.relations:,}"
)

print(
    f"Tags gardés : {handler.kept_tags:,}"
)

print(
    f"Tags retirés: {handler.removed_tags:,}"
)

print()

