#!/usr/bin/env python3
"""Referee: verify every [file-name: "exact quote"] citation in a letter.

Usage: python3 cite-check.py <path/to/letter.md>

Each cited file name is resolved relative to the folder holding the letter.
Each quote must appear verbatim on a single line of that file.
Prints one OK or FAIL line per citation. Exits 0 only if the letter has at
least one citation and every citation checks out; exits 1 otherwise.
"""

import os
import re
import sys

CITATION = re.compile(r'\[([^\[\]":\n]+):\s*"([^"\n]*)"\]')


def main(argv):
    if len(argv) != 2:
        print("usage: python3 cite-check.py <letter path>")
        return 2

    letter_path = argv[1]
    try:
        with open(letter_path, encoding="utf-8") as fh:
            letter = fh.read()
    except OSError as exc:
        print(f"FAIL cannot read letter {letter_path}: {exc}")
        return 1

    folder = os.path.dirname(os.path.abspath(letter_path))
    citations = CITATION.findall(letter)
    if not citations:
        print(f"FAIL no citations found in {letter_path}")
        return 1

    cache = {}
    failures = 0
    for name, quote in citations:
        name = name.strip()
        label = f'[{name}: "{quote}"]'

        if os.path.basename(name) != name or name in ("", ".", ".."):
            print(f"FAIL {label} (file name must be a plain name inside the letter folder)")
            failures += 1
            continue
        if not quote:
            print(f"FAIL {label} (empty quote)")
            failures += 1
            continue

        if name not in cache:
            path = os.path.join(folder, name)
            try:
                with open(path, encoding="utf-8") as fh:
                    cache[name] = fh.read().splitlines()
            except OSError:
                cache[name] = None
        lines = cache[name]

        if lines is None:
            print(f"FAIL {label} (cited file not found)")
            failures += 1
        elif any(quote in line for line in lines):
            print(f"OK   {label}")
        else:
            print(f"FAIL {label} (quote not found verbatim on any single line)")
            failures += 1

    total = len(citations)
    print(f"{total - failures} of {total} citations OK")
    return 1 if failures else 0


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