# Copyright (c) 2023, NVIDIA CORPORATION.  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.


import pynini
from pynini.lib import pynutil

from nemo_text_processing.inverse_text_normalization.ja.graph_utils import (
    NEMO_DIGIT,
    NEMO_NOT_QUOTE,
    GraphFst,
    delete_space,
)


class CardinalFst(GraphFst):
    """
    Finite state transducer for verbalizing cardinals, e.g.
    cardinal { integer: "23" } -> 23
    cardinal { negative: "-" integer: "23" } -> -23
    cardinal { positive: "+" integer: "23" } -> +23
    """

    def __init__(self):
        super().__init__(name="cardinal", kind="verbalize")

        optional_sign = (
            pynutil.delete("negative:")
            + delete_space
            + pynutil.delete("\"")
            + pynini.closure(NEMO_NOT_QUOTE)
            + pynutil.delete("\"")
            + delete_space
        )

        graph = (
            pynutil.delete("integer:")
            + delete_space
            + pynutil.delete("\"")
            + pynini.closure(NEMO_NOT_QUOTE, 1)
            + pynutil.delete("\"")
        )

        exactly_three_digits = NEMO_DIGIT ** 3
        at_most_three_digits = pynini.closure(NEMO_DIGIT, 1, 3)

        group_by_threes = at_most_three_digits + (pynutil.insert(",") + exactly_three_digits).closure()
        graph = graph @ group_by_threes

        final_graph = pynini.closure(optional_sign, 0, 1) + graph

        final_graph = self.delete_tokens(final_graph)
        self.fst = final_graph.optimize()
