#!/usr/bin/env python


import json  # noqa: S003
import os

import click
from babel.messages.pofile import read_po

MINIMUM = 80


def is_translated(msg):
    if isinstance(msg.string, bytes):
        return bool(msg.string)
    for item in msg.string:
        if not item:
            return False
    return True


@click.command()
@click.argument("catalog_file", type=click.Path())
def cli(catalog_file):
    # Read the old ones back.  Once we are in, we will never go.
    with open(catalog_file) as f:
        rv = json.load(f)["supported_locales"]

    base = "src/sentry/locale"
    for locale in os.listdir(base):
        fn = os.path.join(base, locale, "LC_MESSAGES", "django.po")
        if not os.path.isfile(fn):
            continue

        total_count = 0
        translated_count = 0
        with open(fn) as f:
            catalog = read_po(f)
            for msg in catalog:
                total_count += 1
                if is_translated(msg):
                    translated_count += 1
        pct = translated_count / float(total_count) * 100
        click.echo("% -7s % 2d%%" % (locale, pct), err=True)
        if pct >= MINIMUM and locale not in rv:
            rv.append(locale)
    with open(catalog_file, "w") as f:
        json.dump({"supported_locales": sorted(rv)}, f, indent=2)
        f.write("\n")


if __name__ == "__main__":
    cli()