#!/usr/bin/env python3
# check.py: checks that a week plan covers a notes file.
# It checks: every item line of the notes sits under exactly one day heading
# (Monday to Sunday) of the plan, once per time it appears in the notes, and
# every line under a day ends with its source in parentheses: an exact item
# line of the notes, or "answers: " plus one whole line of answers.txt
# (the answers.txt beside the notes file).
# It does NOT check: times, days, bookings, amounts, deadlines, rules, or
# whether the plan is any good. It never reads times.
#
# Notes format: a line starting with "- " is always an item. Any other line in
# capital letters (ignoring text in parentheses) is a heading. Any other
# non-blank line under a heading is an item. Lines before the first heading
# are not items.
#
# Usage: python3 check.py NOTES PLAN
#        python3 check.py --self-test

import os
import re
import shutil
import sys
import tempfile
from collections import Counter

DAYS = ("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")
NOTICE = ("Checked only that every note line is in the plan once, under a day, "
          "and that every plan line says where it came from. Not checked: times, "
          "days, bookings, amounts, deadlines, rules, or whether the plan is a "
          "good one. Read those yourself.")


def is_heading(line):
    if line.startswith("- "):
        return False
    outside = re.sub(r"\([^)]*\)", "", line)
    letters = [c for c in outside if c.isalpha()]
    return bool(letters) and all(c.isupper() for c in letters)


def read_lines(path):
    with open(path, encoding="utf-8") as f:
        return f.read().splitlines()


def note_items(path):
    """Return a list of (line number, text) for every item line."""
    items = []
    in_section = False
    for n, raw in enumerate(read_lines(path), 1):
        line = raw.strip()
        if not line:
            continue
        if line.startswith("- "):
            items.append((n, line))
        elif is_heading(line):
            in_section = True
        elif in_section:
            items.append((n, line))
    return items


def answer_lines(notes_path):
    path = os.path.join(os.path.dirname(os.path.abspath(notes_path)), "answers.txt")
    if not os.path.exists(path):
        return []
    return [l.strip() for l in read_lines(path) if l.strip()]


def day_lines(path):
    """Return (line number, text) for every non-blank line under a day heading."""
    out = []
    in_day = False
    for n, raw in enumerate(read_lines(path), 1):
        line = raw.rstrip()
        if line.lstrip().startswith("#"):
            words = re.findall(r"[A-Za-z]+", line)
            in_day = bool(words) and words[0].lower() in DAYS
            continue
        if in_day and line.strip():
            out.append((n, line.strip()))
    return out


def check(notes_path, plan_path):
    errors = []
    items = note_items(notes_path)
    if not items:
        return ["no item lines found in %s" % notes_path]
    sources = ["(" + text + ")" for _, text in items]
    sources += ["(answers: " + a + ")" for a in answer_lines(notes_path)]
    sources = sorted(set(sources), key=len, reverse=True)

    cited = Counter()
    for n, line in day_lines(plan_path):
        match = next((s for s in sources if line.endswith(s)), None)
        if match is None:
            errors.append("plan line %d does not end with a source from the notes "
                          "or a whole line of answers.txt: %s" % (n, line))
        elif not match.startswith("(answers: "):
            cited[match[1:-1]] += 1

    wanted = Counter(text for _, text in items)
    seen = Counter()
    for n, text in items:
        seen[text] += 1
        if seen[text] > cited[text]:
            errors.append("notes line %d is not under a day in the plan "
                          "(needed %d time(s), found %d): %s"
                          % (n, wanted[text], cited[text], text))
    for text, count in cited.items():
        if count > wanted[text]:
            errors.append("note line is under a day more than once (%d times, "
                          "notes have it %d): %s" % (count, wanted[text], text))
    return errors


def run(notes_path, plan_path):
    errors = check(notes_path, plan_path)
    for e in errors:
        print("  - " + e)
    print(NOTICE)
    print("FAIL" if errors else "PASS")
    return 1 if errors else 0


def self_test():
    here = os.path.dirname(os.path.abspath(__file__))
    tmp = tempfile.mkdtemp(prefix=".selftest-", dir=here)
    notes_text = ("my notes\n\nWORK\nmon 7a-7p\nME\n- dentist thurs 8:15a (cleaning)\n"
                  "- buy milk\n- buy milk\n\nTODO\n- CALL MOM\n")
    answers_text = "car shop is open saturdays\n"
    good_plan = ("## Sort this out first\nnothing\n## Monday\n7a-7p shift (mon 7a-7p)\n"
                 "## Tuesday\nAnytime suggested: milk (- buy milk)\n"
                 "Anytime suggested: milk again (- buy milk)\n"
                 "Anytime suggested: call (- CALL MOM)\n"
                 "## Thursday\n8:15a dentist (- dentist thurs 8:15a (cleaning))\n"
                 "## Saturday\n9a suggested: car (answers: car shop is open saturdays)\n"
                 "## What I assumed\nyear\n")
    cases = [
        ("heading with no blank line before it (ME) read as a heading", None, None, False, None),
        ("a missing item", "7a-7p shift (mon 7a-7p)\n", "", True, "mon 7a-7p"),
        ("an item only in Sort this out first",
         "## Sort this out first\nnothing\n## Monday\n7a-7p shift (mon 7a-7p)\n",
         "## Sort this out first\n7a-7p shift (mon 7a-7p)\n## Monday\n",
         True, "mon 7a-7p"),
        ("a repeated note line kept once", "Anytime suggested: milk again (- buy milk)\n", "",
         True, "buy milk"),
        ("a day line with no source", "7a-7p shift (mon 7a-7p)\n",
         "7a-7p shift (mon 7a-7p)\n7p dinner\n", True, "7p dinner"),
        ("a day line whose answers: text is not a whole line of answers.txt",
         "(answers: car shop is open saturdays)", "(answers: shop closed sunday)", True,
         "shop closed sunday"),
        ("a day line citing only part of an answers.txt line",
         "(answers: car shop is open saturdays)", "(answers: open saturdays)", True,
         "open saturdays"),
        ("an item written in capital letters missing from the plan",
         "Anytime suggested: call (- CALL MOM)\n", "", True, "CALL MOM"),
        ("notes with no items", None, None, True, "no item lines"),
    ]
    all_ok = True
    try:
        with open(os.path.join(tmp, "answers.txt"), "w") as f:
            f.write(answers_text)
        for name, old, new, expect_fail, expect_text in cases:
            notes = notes_text if name != "notes with no items" else "NOTHING HERE\n\nHEADING\n"
            plan = good_plan if old is None else good_plan.replace(old, new, 1)
            if old is not None and plan == good_plan:
                raise RuntimeError("self-test setup broken for: " + name)
            np_, pp = os.path.join(tmp, "notes.txt"), os.path.join(tmp, "plan.md")
            with open(np_, "w") as f:
                f.write(notes)
            with open(pp, "w") as f:
                f.write(plan)
            errors = check(np_, pp)
            if name.startswith("heading"):
                texts = [t for _, t in note_items(np_)]
                ok = not errors and "ME" not in texts and "WORK" not in texts and len(texts) == 5
            else:
                ok = bool(errors) == expect_fail and any(expect_text in e for e in errors)
            all_ok &= ok
            print("%s  %s" % ("ok  " if ok else "BAD ", name))
            for e in errors:
                print("        caught: " + e)
    finally:
        shutil.rmtree(tmp, ignore_errors=True)
    print(NOTICE)
    print("PASS" if all_ok else "FAIL")
    return 0 if all_ok else 1


def main(argv):
    if argv[1:] == ["--self-test"]:
        return self_test()
    if len(argv) != 3:
        print("usage: python3 check.py NOTES PLAN | --self-test")
        print(NOTICE)
        print("FAIL")
        return 2
    return run(argv[1], argv[2])


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