"""Reproduce the two-object counts in §4.1 from UD English GUM r2.16.

Run with Python 3.9+ and an optional path to the three released CoNLL-U files.
The default ranking gives the clear two-object tokens, the number of texts
containing them, and all tokens tagged VERB for each listed lemma. --tokens
outputs the sentence ID and decision for each candidate.
"""

import argparse
import csv
import hashlib
import sys
from collections import Counter, defaultdict
from pathlib import Path


DIGESTS = {
    "dev": "581997015a2d878ad49619032d265a9753e1b6b03d75ca18b04a00bb9ee8991d",
    "test": "fe95c0e744f81cdf2a307ce522604ecc05cd359c7c6d1abaa3a46c85d024f34c",
    "train": "4c00aca285e0f3845bd811dd1fb61a67322bebf5d0317af005d774d167f50c52",
}

# Keys refer to the lexical verb, so two occurrences in a sentence are distinct.
# Wh-complements are set aside whenever the context permits an interrogative
# reading. A possible fused relative is insufficient to count the token as clear.
SET_ASIDE = {
    "Interrogative complement or possible interrogative reading": """
        GUM_court_negligence-19:4 GUM_vlog_radiology-4:19 GUM_vlog_radiology-30:6
        GUM_conversation_artist-32:5 GUM_conversation_atoms-100:2
        GUM_textbook_anthropology-52:9 GUM_vlog_lipstick-23:11
        GUM_whow_overalls-5:4 GUM_news_sensitive-11:6 GUM_podcast_bezos-26:15
        GUM_vlog_studying-12:5 GUM_textbook_anthropology-52:16
        GUM_textbook_spacetime-25:11 GUM_textbook_spacetime-25:18
        GUM_textbook_spacetime-30:12 GUM_vlog_hair-4:13 GUM_whow_elevator-13:3
    """,
    "Incomplete second complement": "GUM_vlog_radiology-24:44 GUM_conversation_erasmus-8:6",
    "Object and object-oriented predicative": "GUM_voyage_oakland-13:23",
    "Comparative duration expression (longer)": "GUM_conversation_blacksmithing-8:10",
    "Function of duration NP with take unresolved": "GUM_fiction_veronique-36:2",
    "Attachment of the following participial predication unresolved": "GUM_fiction_teeth-15:16",
}
EXCEPTIONS = {key: reason for reason, keys in SET_ASIDE.items() for key in keys.split()}


def read_corpus(directory):
    candidates = []
    verb_totals = Counter()
    for split, digest in DIGESTS.items():
        source = directory / f"en_gum-ud-{split}.conllu"
        data = source.read_bytes()
        if hashlib.sha256(data).hexdigest() != digest:
            raise ValueError(f"{source} differs from reviewed release r2.16")
        for block in data.decode("utf-8").strip().split("\n\n"):
            tokens = {}
            objects = defaultdict(lambda: defaultdict(list))
            for line in block.splitlines():
                if line.startswith("# sent_id = "):
                    sentence = line.removeprefix("# sent_id = ")
                fields = line.split("\t")
                if not fields[0].isdigit():
                    continue
                token = int(fields[0])
                tokens[token] = fields
                if fields[3] == "VERB":
                    verb_totals[fields[2].lower()] += 1
                if fields[7] in {"obj", "iobj"}:
                    objects[int(fields[6])][fields[7]].append(token)
            for head, relations in objects.items():
                if tokens[head][3] != "VERB":
                    continue
                indirect, direct = relations["iobj"], relations["obj"]
                if len(indirect) != 1 or len(direct) != 1:
                    continue
                if head < indirect[0] < direct[0]:
                    candidates.append((sentence, head, tokens[head][2].lower()))
    return candidates, verb_totals


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    workspace_data = Path(__file__).resolve().parent / "../../../corpora/ud-english/gum"
    parser.add_argument("directory", nargs="?", type=Path,
                        default=workspace_data if workspace_data.is_dir() else Path.cwd(),
                        help="directory containing the three UD English GUM r2.16 CoNLL-U files")
    parser.add_argument("--tokens", action="store_true", help="show all candidate decisions")
    args = parser.parse_args()
    rows, verb_totals = read_corpus(args.directory)
    keys = {f"{sentence}:{head}" for sentence, head, lemma in rows}
    if len(rows) != len(keys) or EXCEPTIONS.keys() - keys:
        raise ValueError("Candidate IDs do not match the decisions for this release")

    writer = csv.writer(sys.stdout, delimiter="\t", lineterminator="\n")
    counts = Counter()
    documents = defaultdict(set)
    if args.tokens:
        writer.writerow(["sentence", "verb_token", "lemma", "decision"])
    for sentence, head, lemma in rows:
        reason = EXCEPTIONS.get(f"{sentence}:{head}")
        if args.tokens:
            writer.writerow([sentence, head, lemma, reason or "include"])
        if reason is None:
            counts[lemma] += 1
            documents[lemma].add(sentence.rsplit("-", 1)[0])
    if not args.tokens:
        writer.writerow(["lemma", "tokens", "documents", "all_verb_tokens"])
        for lemma in sorted(counts, key=lambda verb: (-counts[verb], verb)):
            writer.writerow([lemma, counts[lemma], len(documents[lemma]), verb_totals[lemma]])


if __name__ == "__main__":
    main()
