#!/usr/bin/env python3

# This script must ideally be run on a configuration that has all drivers enabled...

import glob
import os
import sys

prefixes = {}
prefixes["GTI:"] = "GTI"
prefixes["GMLAS:"] = "GMLAS"
prefixes["HANA:"] = "HANA"
prefixes["PG:"] = "PostgreSQL"
prefixes["MSSQL:"] = "MSSQLSpatial"
prefixes["ES:"] = "Elasticsearch"


def collect_prefix(filename):
    lines = open(filename, "rt").readlines()
    i = -1
    len_lines = len(lines)

    while True:
        i += 1
        if i >= len_lines:
            break
        l = lines[i][0:-1].strip()
        if l.startswith("/*"):
            continue

        pos = l.find('SetMetadataItem(GDAL_DMD_CONNECTION_PREFIX, "')
        if pos > 0:
            pos += len('SetMetadataItem(GDAL_DMD_CONNECTION_PREFIX, "')
            pos_end = l.find('")', pos)
            assert pos_end > 0
            prefix = l[pos:pos_end]
            assert prefix.endswith(":"), prefix
            if prefix not in prefixes:
                prefixes[prefix] = prefix[:-1]


def explore(dirname):
    for filename in glob.glob(dirname + "/*"):
        if os.path.isdir(filename):
            explore(filename)
        if filename.endswith(".cpp"):
            collect_prefix(filename)


for dirname in ("frmts", "ogr"):
    explore(os.path.join(os.path.dirname(__file__), "..", dirname))

ret = 0

has_gdal = False
try:
    from osgeo import gdal

    has_gdal = True
except ImportError:
    pass

if has_gdal:
    # Do a runtime check to verify that there is no missing prefix through source
    # code exploration.
    for i in range(gdal.GetDriverCount()):
        drv = gdal.GetDriver(i)
        connection_prefix = drv.GetMetadataItem(gdal.DMD_CONNECTION_PREFIX)
        if connection_prefix and connection_prefix not in prefixes:
            print(
                "Driver %s report prefix %s, but not found through source code discovery. Manually add it at top of collect_driver_connection_prefix.py"
                % (drv.ShortName, connection_prefix)
            )
            ret = 1
        elif (
            connection_prefix
            and connection_prefix in prefixes
            and prefixes[connection_prefix].upper() != drv.ShortName.upper()
            and drv.ShortName != "PostGISRaster"
        ):
            print(
                "Mismatch between prefix %s and driver name for %s. Manually add it at top of collect_driver_connection_prefix.py"
                % (connection_prefix, drv.ShortName)
            )
            ret = 1

c_file = (
    "// This file was automatically generated by collect_driver_connection_prefix.py\n"
)
c_file += "// DO NOT EDIT\n\n"
c_file += "// clang-format off\n"
c_file += "constexpr static struct {\n"
c_file += "  const char* pszPrefix;\n"
c_file += "  const char* pszDriverName;\n"
c_file += "}\n"
c_file += "asKnownConnectionPrefixes[] =\n"
c_file += "{\n"
for prefix in sorted(prefixes, key=str.lower):
    c_file += f'   {{"{prefix}", "{prefixes[prefix]}"}},\n'
c_file += "};\n"
c_file += "\n"
c_file += "// clang-format on\n"
# print(c_file)

open(
    os.path.join(
        os.path.dirname(__file__), "..", "gcore", "gdal_known_connection_prefixes.h"
    ),
    "wt",
).write(c_file)

sys.exit(ret)
