# Copyright 2024 FBK

# 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

try:
    import pandas as pd
except ImportError:
    print("Please install the pandas package with 'pip install pandas' and try again.")
    exit(1)

import argparse

_VERSION = "1.01"

class ExplicitDefaultsHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
    def _get_help_string(self, action):
        if action.default is None or action.default is False:
            return action.help
        return super()._get_help_string(action)

def main(args):
    """
    This script flags (by setting True the corresponding entry of
    the hall_long_word column) those sentences where at least one
    word is abnormally long; the abnormality is set through the 
    thresh parameter, whose default value is 40.
    """

    if (parsed_args.version): 
        print(f"Version {_VERSION} of anomalous string detector")
        exit(1)

    if not (tsv_files_specified):
        print("--tsv-InFile and --tsv-OutFile are both required")
        parser.print_usage()
        exit(1)

    inDF = pd.read_csv(args.tsv_InFile, sep='\t', dtype=str, low_memory=False, na_filter=False, quoting=3)
    try:
        txt = inDF[parsed_args.column]
    except KeyError:
        print("Error in reading column <"+parsed_args.column+"> in TSV file")
        exit(1)

    flag = []
    for line in txt:
        anomal = False
        try:
            words = line.split()
        except TabError:
            words = []
        for w in words:
            lw=len(w.strip())
            if lw > parsed_args.thresh:
                if args.quiet:
                    flag.append("True")
                else:
                    flag.append("True ("+str(lw)+"): "+w.strip())
                anomal = True
                break
        if not anomal:
            flag.append("False")

    inDF['hall_long_word'] = flag
    inDF.to_csv(args.tsv_OutFile, sep="\t", index=False, quoting=3)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(formatter_class=ExplicitDefaultsHelpFormatter)

    # I/O related arguments
    parser.add_argument(
        '--tsv-InFile', '-i', type=str,
        help="The input TSV file [Mandatory]")

    parser.add_argument(
        '--tsv-OutFile', '-o', type=str,
        help="The output TSV file [Mandatory. If equal to input TSV file, the new column is added to the original file]")

    # Processing arguments:
    parser.add_argument(
        '--column', '-c', default='source',
        help="Column name of the text to process [Optional]")

    parser.add_argument(
        '--thresh', '-t', type=int, default=40,
        help="Max number of chars of a string to be unflagged [Optional]")

    # Reporting related arguments
    parser.add_argument(
        '--quiet', '-q', default=False, action='store_true',
        help='Print only True/False, no explanation for True\'s')

    # Get version information:
    parser.add_argument(
        '--version', '-v', action='store_true', default=False,
        help="Print version of the script and exit")

    
    parsed_args = parser.parse_args()
    tsv_files_specified = \
        getattr(parsed_args, 'tsv_InFile') is not None \
        and len(parsed_args.tsv_InFile) > 0 \
        and getattr(parsed_args, 'tsv_OutFile') is not None \
        and len(parsed_args.tsv_OutFile) > 0

    main(parsed_args)