# (c) Copyright 1996-2012 ECMWF.
# 
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
# In applying this licence, ECMWF does not waive the privileges and immunities 
# granted to it by virtue of its status as an intergovernmental organisation nor
# does it submit to any jurisdiction.

# Documentation is available on Confluence
# https://confluence.ecmwf.int/display/METK/MetKit+configuration


import os
import sys
from collections import OrderedDict
import psycopg2
import yaml

DEFAULT_PORT = 5432

def main():
    try:
        HOST = os.environ['PRODUCT_CATALOGUE_HOST']
        DB = os.environ['PRODUCT_CATALOGUE_DB']
        USER = os.environ['PRODUCT_CATALOGUE_USER']
        PASSWORD = os.environ['PRODUCT_CATALOGUE_PASSWORD']
        PORT = (
            int(os.environ['PRODUCT_CATALOGUE_PORT'])
            if 'PRODUCT_CATALOGUE_PORT' in os.environ
            else DEFAULT_PORT
        )
    except KeyError as e:
        print("ERROR: Environment variable not found: {}".format(e))
        sys.exit(1)

    with psycopg2.connect(host=HOST, dbname=DB, user=USER, password=PASSWORD, port=PORT) as conn:
        with conn.cursor() as cur:
            cur.execute(
                "SELECT DISTINCT class, stream, type, levtype, param::INTEGER FROM fields WHERE param != '' ORDER BY class, stream, type, levtype, param::INTEGER"
            )
            rows = cur.fetchall()

    index = OrderedDict()
    for row in rows:
        cl, stream, type_, levtype, param = row
        key = (cl, stream, type_, levtype)
        if key not in index:
            index[key] = []
        index[key].append(param)
        
    # Manually add type=tf parameters for PGEN
    index[("od", "oper", "tf", "")] = [129, 999]
    index[("od", "scda", "tf", "")] = [129, 999]
    index[("od", "enfo", "tf", "")] = [129, 999]
    
    yaml_dump_data = []
    for key, vals in sorted(index.items()):
        if key[3]:
            yaml_dump_data.append(
                    [{"class":key[0], "stream":key[1], "type":key[2], "levtype":key[3]}, vals]
            )
        else:
            yaml_dump_data.append([{"class":key[0], "stream":key[1], "type":key[2]}, vals])

    with open("params.yaml", "w") as f:
        f.write(
            "# File automatically generated by %s\n# Do not edit\n\n"
            % (os.path.basename(__file__))
        )
        f.write(yaml.safe_dump(yaml_dump_data, default_flow_style=False))


if __name__ == "__main__":
    main()
