#!/usr/bin/env python3
#
# Copyright 2022 Google Inc. All Rights Reserved.
#
# 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.
#
"""Tool to print subsets supported by a given font file.

"""
from pathlib import Path

from fontTools.ttLib import TTFont

from gftools.utils import primary_script
from gftools.util.google_fonts import Metadata, WriteMetadata
from gflanguages import LoadLanguages


def main(args=None):
    import argparse

    parser = argparse.ArgumentParser(
        description="Walk a directory tree and set the primary script"
    )
    parser.add_argument("directory")
    args = parser.parse_args(args)
    for path_obj in Path(args.directory).rglob("METADATA.pb"):
        try:
            metadata = Metadata(path_obj)
        except Exception as e:
            print(f"{path_obj} doesn't conform to font schema: {e}")
            continue
        first_font = path_obj.parent / metadata.fonts[0].filename
        ignore_latin = path_obj.parent.name.startswith("noto")
        script = primary_script(TTFont(first_font), ignore_latin=ignore_latin)
        if not script or script == "Latn":
            continue

        print("%s -> %s" % (path_obj.parent.name, script))
        metadata.primary_script = script

        WriteMetadata(metadata, path_obj)


if __name__ == "__main__":
    main()
