# ver 1.3

import os
import sys


def readfile(filepath: str, encoding: str = 'utf-8'):
    if filepath[0] == '"' and filepath[-1] == '"':
        filepath = filepath[1: -1]
    if not filepath.endswith(".txt"):
        print("输入文件不是 .txt 文件！")
        return []
    try:
        file = open(filepath, encoding=encoding)
        lines = []
        while True:
            line = file.readline().strip()
            if not line:
                break
            lines.append(line)
    except:
        print("文件无法打开！")
        return []
    return lines


def split_line(line: str):
    new_line = line.replace('．', '.')
    new_line = new_line.split('.')[1]
    new_line = new_line.strip()
    return new_line


def compare_lines(line_A: str, line_B: str):
    str_A = split_line(line_A)
    str_B = split_line(line_B)
    if str_A == str_B:
        return True
    return False


def main():
    amount = 1
    if len(sys.argv) != 1:
        amount = len(sys.argv) - 1
    for cur in range(1, amount + 1):
        if len(sys.argv) == 1:
            filepath = input("请将 .txt 文件拖至此处，然后按回车。\n")
        else:
            filepath = sys.argv[cur]
        lines = readfile(filepath)
        if lines == []:
            return 1
        cnt = 0
        for i in range(len(lines)):
            for j in range(len(lines)):
                if i != j and compare_lines(lines[i], lines[j]):
                    cnt += 1
                    print(i + 1, lines[i])
        print("\n共检测到 %d 个重复参考文献。\n\n--------------------\n" % (cnt / 2))
    return 0


if __name__ == "__main__":
    ret = main()
    os.system("pause")
    sys.exit(ret)
