"""인수인계 Markdown 메모의 세 절과 하이픈 목록을 점검한다."""

import argparse
from pathlib import Path


SECTIONS = ("완료한 일", "다음 할 일", "확인할 점")


def check_note(text):
    headings = []
    filled = set()
    current = ""
    fence = ""
    for line in text.splitlines():
        line = line.expandtabs(4)
        if line.startswith("    "):
            continue
        line = line.strip(" ")
        if fence:
            if line.startswith(fence) and not line.strip(fence[0]):
                fence = ""
            continue
        if line.startswith(("```", "~~~")):
            fence = line[: len(line) - len(line.lstrip(line[0]))]
        elif line.startswith("#"):
            current = line[3:].strip() if line.startswith("## ") else ""
            if current:
                headings.append(current)
        elif current and line.startswith("- ") and line[2:].strip():
            filled.add(current)

    errors = []
    if headings != list(SECTIONS):
        errors.append("두 번째 단계 제목을 이 순서로 한 번씩 적으세요: " + " → ".join(SECTIONS))
    for heading in SECTIONS:
        if heading in headings and heading not in filled:
            errors.append("‘{}’ 아래에 '- '로 시작하는 항목을 적으세요.".format(heading))
    return errors


def demo():
    example = """# 검색 화면 수정

## 완료한 일
- 검색어 입력 뒤 결과가 뜨는 것을 확인했다.

## 다음 할 일
- 휴대폰에서 검색 결과를 열어 본다.

## 확인할 점
- 제목이 긴 글도 결과 화면에 들어오는지 확인한다.
"""
    print(example)
    invalid = example.replace("- 휴대폰에서 검색 결과를 열어 본다.", "")
    for label, text, should_pass in (
        ("예시 메모", example, True),
        ("항목을 비운 메모", invalid, False),
    ):
        errors = check_note(text)
        print(label, "·", " / ".join(errors) if errors else "점검 통과")
        if (not errors) != should_pass:
            return 1
    return 0


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    inputs = parser.add_mutually_exclusive_group(required=True)
    inputs.add_argument("--demo", action="store_true", help="통과·실패 예시 실행")
    inputs.add_argument("note", nargs="?", type=Path, help="검사할 UTF-8 Markdown 파일")
    args = parser.parse_args()
    if args.demo:
        return demo()
    try:
        errors = check_note(args.note.read_text(encoding="utf-8-sig"))
    except (OSError, UnicodeError) as error:
        parser.exit(2, "파일을 읽을 수 없습니다: {}\n".format(error))
    if errors:
        print("\n".join(errors))
        return 1
    print("점검 통과 · 세 제목과 항목을 확인했습니다.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
