#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=C0301, R1710

""" titlemd """

import argparse
import sys

try:
    from titlecase import titlecase
except ImportError:
    print("Please install titlecase")

def arg_parse():
    """
    Argument parser
    """
    parser = argparse.ArgumentParser(
        description="Titlemd"
    )
    parser.add_argument('-t', '--test',
                        action='store_true',
                        help="test")
    parser.add_argument('location',
                        nargs='?',
                        default='.',
                        help="location, default current directory")
    return parser.parse_args()

def mkdocs_available(location):
    """ Is mkdocs.yml available? """
    return "mkdocs.yml" in location

def linestart(line, disabled, test, prev_line=None):
    """ linestart """
    if test:
        if (line.startswith("``") or line.startswith("extra:")) and not disabled:
            return True
        if (line.startswith("``") or (prev_line and prev_line.startswith("pages:"))) and disabled:
            return False
    else:
        if line.startswith("``") and not disabled:
            return True
        if line.startswith("``") and disabled:
            return False
    return disabled

def testdata(arg):
    """ test """
    # Spelling exceptions
    with open('.spelling', encoding='utf-8') as fdata:
        spelling = fdata.readlines()

    def abbreviations(word, **_):
        """ abbreviations """
        if word + "\n" in spelling:
            return word

    # Open the file and read the lines as a list
    with open(arg.location, encoding='utf-8') as fdata:
        lines = fdata.readlines()

    # Loop through the list of lines and titlecase
    # any line beginning with '#'.
    return_value = 0
    prev_line = lines[0] if lines else ""
    echo_filename = False
    disabled = mkdocs_available(arg.location)
    for line in lines:
        disabled = linestart(line, disabled, arg.test, prev_line)
        if line.startswith('#') and not disabled and not mkdocs_available(arg.location):
            title_line = titlecase(line[:line.find("]")], callback=abbreviations) + line[line.find("]"):]
            if line != title_line:
                if return_value == 0 and not echo_filename:
                    print(f"{arg.location}")
                    echo_filename = True
                print(f"-{line}", end="")
                print(f"+{title_line}", end="")
                print()
                return_value = 1
        if (line.startswith('---') or line.startswith('===')) and not disabled:
            title_prev_line = titlecase(prev_line[:prev_line.find("]")], callback=abbreviations) + prev_line[prev_line.find("]"):]
            if prev_line != title_prev_line:
                if return_value == 0 and not echo_filename:
                    print(f"{arg.location}")
                    echo_filename = True
                print(f"-{prev_line}", end="")
                print(f"+{title_prev_line}", end="")
                print()
                return_value = 1
        if (mkdocs_available(arg.location) and not line.startswith('#') and not disabled):
            title_line = titlecase(line[:line.find(":")], callback=abbreviations) + line[line.find(":"):]
            if line != title_line:
                if return_value == 0 and not echo_filename:
                    print(f"{arg.location}")
                    echo_filename = True
                print(f"-{line}", end="")
                print(f"+{title_line}", end="")
                print()
                return_value = 1
        prev_line = line
    return return_value

def writedata(arg):
    """ writedata """
    # Spelling exceptions
    with open('.spelling', encoding='utf-8') as fdata:
        spelling = fdata.readlines()

    def abbreviations(word, **_):
        """ abbreviations """
        if word + "\n" in spelling:
            return word

    # Open the file and read the lines as a list
    with open(arg.location, encoding='utf-8') as fdata:
        lines = fdata.readlines()

    with open(arg.location, 'w', encoding='utf-8') as fdata:
        prev_line = lines[0] if lines else ""
        disabled = False
        for line in lines:
            disabled = linestart(line, disabled, arg.test)
            if line.startswith('#') and not disabled:
                line = titlecase(line[:line.find("]")], callback=abbreviations) + line[line.find("]"):]
            if (line.startswith('---') or line.startswith('===')) and not disabled:
                prev_line = titlecase(prev_line[:prev_line.find("]")], callback=abbreviations) + prev_line[prev_line.find("]"):]
            fdata.write(prev_line)
            prev_line = line
        fdata.write(prev_line)

def main():
    """
    main function
    """

    arg = arg_parse()

    if arg.test:
        sys.exit(testdata(arg))
    else:
        writedata(arg)

if __name__ == "__main__":
    main()