#!/usr/bin/env python3
"""The stamp of the addon's texts in resources/language/resource.language.en_gb/strings.po (wcs/skin/texts.py,
docs/plan/skin-milionar/251-texts-after-update.md).

A hash of every strings.po (the stamp entry left out). The service compares
Kodi's copy of the stamp with the file's: differ, Kodi reloads the addon's texts. release.py writes it at every
release.

  python3 scripts/strings_stamp.py          write it (prints the stamp)
  python3 scripts/strings_stamp.py check    exit 1 when the file's stamp is not current
"""
import hashlib
import os
import re
import sys

ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
LANGUAGE = os.path.join(ROOT, 'resources', 'language')
EN = os.path.join(LANGUAGE, 'resource.language.en_gb', 'strings.po')
STAMP_ID = 39999                                   # wcs.skin.texts.STAMP_ID
ENTRY = re.compile(r'msgctxt "#%d"\nmsgid "[^"]*"\nmsgstr ""\n\n' % STAMP_ID)
HEADER_END = '"Language: en\\n"\n\n'


def _read(path):
    with open(path, encoding='utf-8') as handle:
        return handle.read()


def compute(root=ROOT):
    language = os.path.join(root, 'resources', 'language')
    digest = hashlib.sha1()
    for name in sorted(os.listdir(language)):
        path = os.path.join(language, name, 'strings.po')
        if os.path.isfile(path):
            digest.update(name.encode('utf-8') + b'\0')
            digest.update(ENTRY.sub('', _read(path)).encode('utf-8') + b'\0')
    return 'texts-' + digest.hexdigest()[:16]


def current(root=ROOT):
    match = re.search(r'msgctxt "#%d"\nmsgid "([^"]*)"' % STAMP_ID,
                      _read(os.path.join(root, 'resources', 'language', 'resource.language.en_gb', 'strings.po')))
    return match.group(1) if match else ''


def write(root=ROOT):
    path = os.path.join(root, 'resources', 'language', 'resource.language.en_gb', 'strings.po')
    text = ENTRY.sub('', _read(path))
    if HEADER_END not in text:
        raise SystemExit('en_gb strings.po: header not found')
    stamp = compute(root)
    entry = 'msgctxt "#{}"\nmsgid "{}"\nmsgstr ""\n\n'.format(STAMP_ID, stamp)
    text = text.replace(HEADER_END, HEADER_END + entry, 1)    # the first entry: the service reads only the head
    with open(path, 'w', encoding='utf-8') as handle:
        handle.write(text)
    return stamp


def main():
    if sys.argv[1:] == ['check']:
        wanted, found = compute(), current()
        if wanted != found:
            print('strings stamp {!r} is not current {!r}: run scripts/strings_stamp.py'.format(found, wanted))
            sys.exit(1)
        print('strings stamp current: ' + found)
    else:
        print(write())


if __name__ == '__main__':
    main()
