# 社外に出すメールの下書きを、出す前に機械で見る。
#
# 使い方:
#   python tools/mail_check.py 下書き.txt
#   python tools/mail_check.py 下書き.txt --ng 社内語.txt
#
# 見るのは、敬称の付け方と、二重敬語と、社外に出さない語の3つ。
# 文の意味は見ない。中身が合っているかは別に確かめる。
import re
import sys

try:
    sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

YAKUSHOKU = "社長|副社長|専務|常務|部長|次長|課長|係長|室長|所長|主任|会長|支店長|店長"

RULES = [
    ("御中と様を一緒に使っている", re.compile(r"御中[^\n]{0,20}(様|殿)|(様|殿)[^\n]{0,20}御中")),
    ("各位に様か殿を付けている", re.compile(r"各位\s*(様|殿)")),
    ("役職に様を付けている", re.compile(r"(" + YAKUSHOKU + r")\s*(様|殿)")),
    ("二重敬語", re.compile(r"(お|ご)[^\s。、]{1,8}(さ|し)せていただ|"
                        r"拝[見読聴借]させていただ|お伺いさせていただ")),
    ("のほう を付けている", re.compile(r"[ぁ-んァ-ヶ一-龥]の(ほう|方)(を|が|に|で)")),
    ("社外で使わない語", re.compile(r"了解(しました|です)|ご苦労(様|さま)|取り急ぎ|"
                            r"ご査収ください[^。]*よろしく[^。]*ご査収")),
    ("半角カナ", re.compile(r"[｡-ﾟ]")),
    ("宛名に会社名だけで敬称がない", re.compile(r"^[^\n]*(株式会社|有限会社|合同会社)"
                                r"[^\n]*$(?<!御中)(?<!様)", re.M)),
]


def check(text: str, ng: list[str]) -> list[tuple[str, int, str]]:
    out = []
    lines = text.split("\n")
    for i, line in enumerate(lines, start=1):
        for name, rx in RULES:
            if name == "宛名に会社名だけで敬称がない" and i > 5:
                continue
            m = rx.search(line)
            if m:
                out.append((name, i, m.group(0)[:30]))
        for w in ng:
            if w and w in line:
                out.append(("社内の語が残っている", i, w))
    return out


def main() -> int:
    args = [a for a in sys.argv[1:] if not a.startswith("--")]
    if not args:
        print("python tools/mail_check.py 下書き.txt [--ng 社内語.txt]")
        return 1
    ng: list[str] = []
    if "--ng" in sys.argv:
        path = sys.argv[sys.argv.index("--ng") + 1]
        ng = [w.strip() for w in open(path, encoding="utf-8").read().split("\n") if w.strip()]
    text = open(args[0], encoding="utf-8").read()
    found = check(text, ng)
    print(f"{args[0]} / {len(text.splitlines())}行 / 指摘 {len(found)}件")
    for name, line, hit in found:
        print(f"  {line:>3}行目 {name}: {hit}")
    return 1 if found else 0


if __name__ == "__main__":
    sys.exit(main())
