"""Count the ten patterns by a vote of three independent readings, and write vote_counts.json for the page.

Usage:
    python3 vote.py

Three readings of all 51 articles against the same definitions (CODEBOOK2.md): codes/v2-A.json and codes/v2-B.json
by Claude, codes/codex.json by GPT. A reading's yes counts only when its passage is found word for word in the
article (whitespace collapsed). Nothing is ruled on afterwards: a pattern is counted for an article when at least
two of the three readings said yes. "all" is the articles where all three said yes and "any" where at least one did.
A team size counts when at least two readings give the same number.
"""

import collections
import json
import pathlib
import re

HERE = pathlib.Path(__file__).parent
PATTERNS = ["CUT", "START", "DEPTH", "A11Y", "FEEDBACK", "MOTION", "DEVICE", "CONVENTION", "VOICE", "USERS"]
READINGS = {"claude_1": "v2-A.json", "claude_2": "v2-B.json", "gpt": "codex.json"}


def flat(text: str) -> str:
    """Collapse whitespace so a passage that spans a line break still matches."""
    return re.sub(r"\s+", " ", text).strip()


def main() -> None:
    """Verify every passage, take the vote, and write vote_counts.json."""
    index = {r["id"]: r for r in json.loads((HERE / "index.json").read_text())}
    article = {i: flat((HERE / "articles" / f"{i}.txt").read_text()) for i in index}
    yes, teams, rejected = {}, {}, 0
    for reading, name in READINGS.items():
        rows = json.loads((HERE / "codes" / name).read_text())
        assert sorted(r["id"] for r in rows) == sorted(index), reading
        for row in rows:
            for pattern in PATTERNS:
                code = row["codes"][pattern]
                if not code["present"]:
                    continue
                if len(code["quote"].split()) >= 5 and flat(code["quote"]) in article[row["id"]]:
                    yes.setdefault((row["id"], pattern), {})[reading] = flat(code["quote"])
                else:
                    rejected += 1
            if row.get("team") is not None and row.get("team_quote") and flat(row["team_quote"]) in article[row["id"]]:
                teams.setdefault(row["id"], []).append(int(row["team"]))
    out = {"articles": len(index), "readings": list(READINGS), "passages_rejected": rejected,
           "calls": {"all_three": sum(1 for v in yes.values() if len(v) == 3), "two": sum(1 for v in yes.values() if len(v) == 2), "one": sum(1 for v in yes.values() if len(v) == 1), "one_claude": sum(1 for v in yes.values() if len(v) == 1 and "gpt" not in v),
                     "claude_without_gpt": sum(1 for v in yes.values() if "gpt" not in v)},
           "patterns": {}}
    for pattern in PATTERNS:
        rows = sorted(({"id": i, "app": index[i]["app"], "readings": len(v), "quote": next(iter(v.values()))} for (i, p), v in yes.items() if p == pattern and len(v) >= 2), key=lambda r: r["id"])
        out["patterns"][pattern] = {"count": len(rows), "all": sum(1 for (i, p), v in yes.items() if p == pattern and len(v) == 3),
                                    "any": sum(1 for (i, p), v in yes.items() if p == pattern), "articles": rows}
    claude = [json.loads((HERE / "codes" / READINGS[k]).read_text()) for k in ("claude_1", "claude_2")]
    second = {row["id"]: row for row in claude[1]}
    out["claude_readings"] = {"decisions": len(index) * len(PATTERNS),
                              "agree": sum(bool(row["codes"][p]["present"]) == bool(second[row["id"]]["codes"][p]["present"]) for row in claude[0] for p in PATTERNS)}
    out["teams"] = {}
    for i, sizes in sorted(teams.items()):
        size, votes = collections.Counter(sizes).most_common(1)[0]
        if votes >= 2:
            out["teams"][i] = size
    (HERE / "vote_counts.json").write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n")
    print(out["calls"], "rejected", rejected)
    for pattern in sorted(PATTERNS, key=lambda p: -out["patterns"][p]["count"]):
        v = out["patterns"][pattern]
        print(f"{pattern:11} two or more {v['count']:2}   all three {v['all']:2}   any {v['any']:2}")
    sizes = sorted(out["teams"].values())
    print("teams", len(sizes), "three or fewer", sum(1 for n in sizes if n <= 3), "solo", sizes.count(1), sizes)


if __name__ == "__main__":
    main()
