#!/usr/bin/python
#
# Copyright 2024 Google LLC
#
# 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.

"""
generate.py - take generic template and process to different languages.
"""

import difflib
import sys


# Language / Template folder name
TEMPLATES = {
    "python": "templates/index.html",
    "nodejs": "views/index.handlebars",
    "java": "src/main/resources/templates/index.html",
}

for lang in TEMPLATES.keys():
    with open("app/templates/index.html.tmpl") as html:
        output = []

        output.append(
            "<!--- Generated by 'make generate'. Do not manually edit. -->\n"
        )

        java_javascript_flag = False
        for line in html.readlines():

            # Flip operator for different types of thymeleaf syntax.
            if 'th:inline="javascript"' in line:
                if lang == "java":
                    # mark we're using alternative var syntax
                    java_javascript_flag = True
                else:
                    # remove java syntax helper (noop in other langs)
                    line = line.replace(' th:inline="javascript"', "")

            # Language-specific placements for various logic
            if "##" in line:
                if "##VALUE" in line:
                    if lang == "python" or lang == "nodejs":
                        front_replace, back_replace = "{{ ", " }}"
                    elif lang == "java":
                        if java_javascript_flag:
                            front_replace, back_replace = (
                                "/*[[${",
                                "}]]*/ 'default'",
                            )
                        else:
                            front_replace, back_replace = (
                                '<span th:text="${',
                                '}"></span>',
                            )

                    line = line.replace("##VALUE(", front_replace).replace(
                        ")##", back_replace
                    )

                if "##LIST" in line:
                    if lang == "python":
                        front_replace, back_replace = "{{ ", " }}"
                    elif lang == "nodejs":
                        front_replace, back_replace = "[{{ ", " }}]"
                    elif lang == "java":
                        if java_javascript_flag:
                            front_replace, back_replace = (
                                "/*[[${",
                                "}]]*/ 'default'",
                            )
                        else:
                            front_replace, back_replace = (
                                '<span th:text="${',
                                '}"></span>',
                            )

                    line = line.replace("##LIST(", front_replace).replace(
                        ")##", back_replace
                    )

                if "##IF SQUIRRELS##" in line:
                    if lang == "python":
                        replacement = "{% if squirrel_count > 0 %}"
                    elif lang == "nodejs":
                        replacement = "{{#if squirrel_count}}"
                    elif lang == "java":
                        replacement = '<span th:if="${squirrel_count} > 0">'

                    line = line.replace("##IF SQUIRRELS##", replacement)

                if "##ELSE" in line:
                    if lang == "python":
                        replace = "{% else %}"
                    elif lang == "nodejs":
                        replace = "{{else}}"
                    elif lang == "java":
                        replace = (
                            '</span><span th:unless="${squirrel_count} > 0">'
                        )
                    line = line.replace("##ELSE", replace)

                if "##ENDIF" in line:
                    if lang == "python":
                        replace = "{% endif %}"
                    elif lang == "nodejs":
                        replace = "{{/if}}"
                    elif lang == "java":
                        replace = "</span>"
                    line = line.replace("##ENDIF", replace)

            output.append(line)

    html_output = f"app/{lang}/{TEMPLATES[lang]}"

    # Check if any changes are required to be made, error 1 if updates needed
    if "--validate" in sys.argv:
        with open(html_output, "r") as f:
            original = f.readlines()

        diffs = []
        for line in difflib.unified_diff(
            original,
            output,
            fromfile=html_output,
            tofile=f"(new {html_output})",
        ):
            diffs += line

        if len(diffs) == 0:
            print(f"{lang} generated output identical. No differences.")
        else:
            print(f"\n❌ {lang} differences Need to run `make generate`.\n")
            print("".join(diffs))
            sys.exit(1)

    else:
        # Write results
        with open(html_output, "w") as f:
            for line in output:
                f.write(line)

        print(f"Wrote {html_output}")
