#!/usr/bin/python3
# vim:se tw=0 sts=4 ts=4 et ai:
"""
Copyright © 2024 Osamu Aoki

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
"""
import argparse
import locale
import collections
import sys
import xml.etree.ElementTree as ET

#######################################################################
# Global variables
#######################################################################
verbose = 0  # quiet
# verbose = 1: default
# verbose = 2: verbose
# verbose = 3: debug


#######################################################################
# main: parse command line parser
#######################################################################
def main():
    locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
    parser = argparse.ArgumentParser(
        description="""\
xml tag checker for po-file

When PO file is generated from DocBook XML or similar file, it will contain
some XML markers.  Many translation errors come from typos around such markers.

This checker will find unmatched set of XML markers between msgid a msgstr.

Return 0, if no error.  Return count of errors, if the error is found.

copyright 2024 Osamu Aoki <osamu@debian.org>
license: MIT

"""
    )
    parser.add_argument("-v", "--verbose", action="count", default=1, help="verbose")
    parser.add_argument(
        "-m",
        "--msg",
        action="store_true",
        default=False,
        help="print msgid and msgstr for each error",
    )
    parser.add_argument(
        "-f",
        "--test-fuzzy",
        action="store_true",
        default=False,
        help="test applies to fuzzy msg too",
    )
    parser.add_argument("pofile", help="po file to be analyzed")
    #######################################################################
    # generate argument parser instance
    #######################################################################
    args = parser.parse_args()
    # verbose = args.verbose
    #######################################################################
    state = ""  # "msgid"/"msgstr"/""
    state_last = ""
    msgid_str = ""
    msgstr_str = ""
    fuzzy = False
    msgstr_lnum = 0
    error_count = 0
    with open(args.pofile, "r") as fp:
        for lnum, line in enumerate(fp.readlines()):
            line = line.strip()  # remove NL
            if line.startswith("msgid"):
                state = "msgid"
                msgid_str = line[len("msgid ") :].strip()[1:-1]
            elif line.startswith("msgstr"):
                state = "msgstr"
                msgstr_lnum = lnum
                msgstr_str = line[len("msgstr ") :].strip()[1:-1]
            elif line.startswith('"'):
                if state == "msgid":
                    msgid_str += line[1:-1]
                elif state == "msgstr":
                    msgstr_str += line[1:-1]
                else:
                    # line number should start at 1 like editor
                    print("E: **INVALID** PO file line={}: '{}'".format(lnum + 1, line))
                    sys.exit(2)
            elif line.startswith("#") and "fuzzy" in line:
                state = "#"
                fuzzy = True
            elif line.startswith("#"):
                state = "#"
            else:
                state = ""
            if state == "" and state_last == "msgstr":
                fuzzy_in = fuzzy
                fuzzy = False
                # ready to report
                # print("I: ----------------------------------------------------------")
                if msgid_str == "" or msgstr_str == "" or "<" not in msgid_str:
                    # notworth analyzing
                    continue
                if not args.test_fuzzy and fuzzy_in:
                    # test_fuzzy=*,     fuzzy_in=False -> test
                    # test_fuzzy=True,  fuzzy_in=True  -> test
                    # test_fuzzy=False, fuzzy_in=True  -> don't test
                    continue
                # normalize
                msgid_str = msgid_str.replace("xl:href", "href").replace('\\"', '"')
                msgstr_str = msgstr_str.replace("xl:href", "href").replace('\\"', '"')
                # msgstr is not "" and msgid may have XML tag
                xml_msgid = ET.fromstring("<msg></msg>")
                xml_msgstr = ET.fromstring("<msg></msg>")
                err0_str = ""
                try:
                    xml_msgid = ET.fromstring("<msg>" + msgid_str + "</msg>")
                except ET.ParseError as err0:
                    valid_msgid = False
                    # look for error position
                    col0 = max(err0.position[1] - len("<msg>"), 0)
                    err0_str = msgid_str[col0 : col0 + 20]
                except Exception as err0:
                    valid_msgid = False
                    print(f"err0 unexpected {err0=}, {type(err0)=}")
                else:
                    valid_msgid = True
                err1_str = ""
                try:
                    xml_msgstr = ET.fromstring("<msg>" + msgstr_str + "</msg>")
                except ET.ParseError as err1:
                    valid_msgstr = False
                    # look for error position
                    col1 = max(err1.position[1] - len("<msg>"), 0)
                    err1_str = msgstr_str[col1 : col1 + 20]
                except Exception as _:
                    valid_msgstr = False
                else:
                    valid_msgstr = True
                if valid_msgid and valid_msgstr:
                    tags_msgid = collections.Counter(
                        [element.tag for element in xml_msgid.iter()]
                    )
                    del tags_msgid["msg"]
                    tags_msgstr = collections.Counter(
                        [element.tag for element in xml_msgstr.iter()]
                    )
                    del tags_msgstr["msg"]
                    if tags_msgid == tags_msgstr:
                        # print("I: line={} valid XML and       matched XML tags msgid={}".format(msgstr_lnum, tags_msgid))
                        pass
                    else:
                        # line number should start at 1 like editor
                        print(
                            "E: line={} **UNMATCHED XML TAG: fuzzy={} tags_msgid={} tags_msgstr={}".format(
                                msgstr_lnum + 1, fuzzy_in, tags_msgid, tags_msgstr
                            )
                        )
                        if args.msg:
                            print("   msgid  = '{}'".format(msgid_str))
                            print("   msgstr = '{}'".format(msgstr_str))
                        error_count += 1
                else:
                    # line number should start at 1 like editor
                    print(
                        "E: line={} **INVALID** XML: fuzzy={} error at msgid='{}' msgstr='{}' (truncated)".format(
                            msgstr_lnum + 1, fuzzy_in, err0_str, err1_str
                        )
                    )
                    if args.msg:
                        print("   msgid  = '{}'".format(msgid_str))
                        print("   msgstr = '{}'".format(msgstr_str))
                    error_count += 1
            state_last = state
        print("ERROR COUNT = {}".format(error_count))
        sys.exit(error_count)


#######################################################################
# Test code
#######################################################################
if __name__ == "__main__":
    main()
# vim:set sw=4 sts=4:
