#
#  Copyright (c) 2021-2023.  Joël Larose
#
#  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.
#
#
"""Simple python script to convert the out_file of mypy's xml into a score that
anybadge can use."""

import sys
from argparse import ArgumentParser, FileType, RawTextHelpFormatter
from importlib.resources import files, as_file
from typing import TextIO, Optional

from lxml import etree

def main(prog: Optional[str] = None) -> None:
    """Entry point for the command line."""

    parser = ArgumentParser(description="Generates a mypy score.",
                            prog=prog,
                            formatter_class=RawTextHelpFormatter)
    default_xslt = _default_xslt()
    parser.add_argument(
            '-s', '--stylesheet',
            help="The XSLT stylesheet used to process the in_file XML to the out_file TXT"
            "\n(Optional, default: built-in stylesheet)",
            default=default_xslt, type=open
    )
    parser.add_argument(
            '-i', '--input',
            help="The index to the XML files generated by mypy"
            "\n(Required)",
            # default=".tmp/index.xml",  # Debugging only
            type=open
    )
    parser.add_argument(
            '-o', '--output',
            help="The file to which the score will be recorded"
            "\n(Optional, default: stout)",
            default=sys.stdout, type=FileType('w')
    )

    args = parser.parse_args()

    processor(args.stylesheet, args.input, args.output)

    args.stylesheet.close()
    args.input.close()
    args.output.close()


def _default_xslt() -> str:
    cm = as_file(files("mypy_xml_score").joinpath("mypy_xml_score.xslt"))
    with cm as file:
        return str(file)


def processor(stylesheet: TextIO, in_file: TextIO, out_file: TextIO) -> None:
    """Takes the stylesheet and the in_file, generates a score, and writes it to out_file."""

    xslt = etree.parse(stylesheet)
    transform = etree.XSLT(xslt)

    mypy_index = etree.parse(in_file)
    result = transform(mypy_index)

    out_file.write(str(result))
