#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


from __future__ import annotations

import pathlib
import re
import sys
import uuid

import click

from edb.tools.edb import edbcommands


def die(msg):
    print(f'FATAL: {msg}', file=sys.stderr)
    sys.exit(1)


def main(*, stdout: bool):
    import edb
    for p in edb.__path__:  # type: ignore[attr-defined]
        ep = pathlib.Path(p) / 'api' / 'types.txt'
        if ep.exists():
            out_fn = pathlib.Path(p) / 'schema' / '_types.py'
            break
    else:
        die('Unable to find the "edb/api/types.txt" file')

    items_code = []
    with open(ep, 'rt') as f:
        for line in f.readlines():
            if re.match(r'(?x)^ (\s*\#[^\n]*) | (\s*) $', line):
                continue

            parts = re.split(r'\s+', line.strip())
            tid, name = parts

            items_code.append(
                f'    sn.name_from_string({name!r}):\n'
                f'        {uuid.UUID(tid)!r},')

    code = (
        f'# AUTOGENERATED FROM "edb/api/types.txt" WITH\n'
        f'#    $ edb gen-types'
        f'\n\n\n'
        f'from __future__ import annotations'
        f'\n'
        f'from typing import *  # NoQA'
        f'\n\n\n'
        f'import uuid'
        f'\n\n'
        f'from edb.common import uuidgen'
        f'\n'
        f'from edb.schema import name as sn'
        f'\n\n\n'
        f'UUID: Type[uuid.UUID] = uuidgen.UUID'
        f'\n\n\n'
        f'TYPE_IDS = {{'
        f'\n' +
        "\n".join(items_code) +
        f'\n'
        f'}}'
        f'\n'
    )

    if stdout:
        print(code, end='')
    else:
        with open(out_fn, 'wt') as f:
            f.write(code)


@edbcommands.command('gen-types')
@click.option(
    '--stdout', type=bool, default=False, is_flag=True)
def gen_types(*, stdout):
    """Generate edb/schema/_types.py from edb/api/types.txt"""
    try:
        main(stdout=stdout)
    except Exception as ex:
        die(str(ex))
