#!/usr/bin/env python3
# -*- coding: utf-8 -*-

##################################################
#
# make_fsg.py
#
# This module takes a text file, marked up with
# units (e.g. w for word, m for morpheme) and ids
# and converted to IPA, and outputs a FSG
# file for processing by PocketSphinx.
#
# TODO: AP: This docstring seems to have been copied from make_fsg
#           and doesn't appear to be used. Do we need this file?
##################################################


from __future__ import absolute_import, division, print_function, unicode_literals

import argparse
import datetime
import os

import pystache

from readalongs.text.util import load_xml, save_txt

JSGF_TEMPLATE = """#JSGF 1.0 UTF-8;
grammar {{name}};

/**
    * Auto-generated JSGF grammar for the document {{name}}.
    *
    * @author Automatically generated by make_jsgf.py
    * @version 1.0
    * @since {{date}}
    */

public <s> = {{#words}} {{id}} {{/words}} ;
"""


def make_jsgf(xml, filename, unit="m"):
    data = {
        "name": os.path.splitext(os.path.basename(filename))[0],
        "date": datetime.datetime.today().strftime("%Y-%m-%d"),
        "words": [],
    }

    for e in xml.xpath(".//" + unit):
        if "id" not in e.attrib:  # don't put in elements with no id
            continue
        text = e.text.strip()
        if text == "":  # don't put in elements with no text
            continue
        id = e.attrib["id"]
        data["words"].append({"id": id})

    return pystache.render(JSGF_TEMPLATE, data)


def go(input_filename, output_filename, unit):
    xml = load_xml(input_filename)
    jsgf = make_jsgf(xml, input_filename, unit)
    save_txt(output_filename, jsgf)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Make an JSGF grammar from an XML file with IDs"
    )
    parser.add_argument("input", type=str, help="Input XML")
    parser.add_argument("output_jsgf", type=str, help="Output .jsgf file")
    parser.add_argument(
        "--unit",
        type=str,
        default="m",
        help="XML tag of the unit of analysis " '(e.g. "w" for word, "m" for morpheme)',
    )
    args = parser.parse_args()
    go(args.input, args.output_fsg, args.unit)
