#!/usr/bin/env python3
"""Asks: open GitHub review requests and assigned issues, every account.

    bin/asks            ask GitHub, write .summary/github-asks.json, print one line
    bin/asks --print    the same, and print the file

For each account in config.json `github_accounts` (`login` and `side`,
personal or work; `gh` must be logged into each), read-only searches:

    gh search prs    --review-requested=@me --state=open
    gh search prs    user-review-requested:@me --state=open
    gh search issues --assignee=@me --state=open   (pull requests left out)

The first finds every open request for the user's review, their own and
their teams'; the second only those asked of them by name. So each review
carries `via`: "you" (asked of the user) or "team" (asked of a team they are
in). bin/foryou gives a "you" ask or an assigned issue its own Needs you item
and folds "team" asks into one item per account.

Each hit is kept as a note, nothing more: title,
repo, who asked, when, link, side, and the project whose page names that repo
(projects/*.md, a `github.com/<owner>/<repo>` on the page). Nothing from the
PR body, the diff or the comments is fetched, for either side.

bin/foryou reads the file and turns each ask into a Needs you item. bin/foryou
itself never touches the network; this file is the only part that does.

The token stays in gh's keychain: it is passed to the child `gh` as GH_TOKEN
for one call and never written anywhere.

In a demo folder (`demo: true`) it asks nothing, writes nothing, and says
NOT ESTABLISHED.

Exit status: 0 written (an account that failed is named in the file and the
line, the rest still written); 1 no account answered.
"""
import datetime
import glob
import json
import os
import re
import subprocess
import sys

sys.dont_write_bytecode = True  # no __pycache__ beside the engine's scripts
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import lifecfg  # noqa: E402

LIFE = lifecfg.root()
OUT = os.path.join(LIFE, ".summary", "github-asks.json")
ACCOUNTS = tuple((a["login"], a.get("side", "personal"))
                 for a in lifecfg.config(LIFE)["github_accounts"] if a.get("login"))
FIELDS = "url,title,repository,author,createdAt"


def gh(user, *args):
    try:
        tok = subprocess.run(["gh", "auth", "token", "--user", user], capture_output=True, text=True, timeout=20)
        if tok.returncode != 0:
            return None, "not logged in to gh"
        env = dict(os.environ, GH_TOKEN=tok.stdout.strip())
        p = subprocess.run(["gh"] + list(args), capture_output=True, text=True, timeout=60, env=env)
    except (OSError, subprocess.TimeoutExpired) as e:
        return None, str(e)
    if p.returncode != 0:
        return None, (p.stderr.strip().splitlines() or ["gh failed"])[-1]
    try:
        return json.loads(p.stdout or "[]"), None
    except ValueError:
        return None, "gh printed something that is not JSON"


def repo_projects():
    """owner/repo (lower case) -> project slug, from each project page."""
    out = {}
    for path in sorted(glob.glob(os.path.join(LIFE, "projects", "*.md"))):
        slug = os.path.basename(path)[:-3]
        text = open(path, encoding="utf-8").read()
        for m in re.finditer(r"github\.com/([\w-]+/[\w.-]*[\w-])", text):
            out.setdefault(re.sub(r"\.git$", "", m.group(1)).lower(), slug)
    return out


def note(hit, kind, user, side, projects, via="you"):
    repo = hit["repository"]["nameWithOwner"]
    return {"kind": kind, "via": via, "account": user, "side": side, "title": hit["title"], "repo": repo,
            "who": hit["author"]["login"], "bot": bool(hit["author"].get("is_bot")) or "[Snyk]" in hit["title"],
            "since": hit["createdAt"][:10], "link": hit["url"], "project": projects.get(repo.lower())}


def main(argv):
    if lifecfg.demo(LIFE):
        print("asks: NOT ESTABLISHED, demo folder: GitHub is not asked")
        return 0
    if not ACCOUNTS:
        print("asks: no accounts in config.json `github_accounts`, nothing asked", file=sys.stderr)
        return 1
    projects = repo_projects()
    asks, failed = [], {}
    for user, side in ACCOUNTS:
        prs, err = gh(user, "search", "prs", "--review-requested=@me", "--state=open",
                      "--json", FIELDS, "--limit", "100")
        mine, err3 = gh(user, "search", "prs", "user-review-requested:@me", "--state=open",
                        "--json", "url", "--limit", "100")
        direct = {h["url"] for h in mine or []}
        issues, err2 = gh(user, "search", "issues", "--assignee=@me", "--state=open",
                          "--json", FIELDS + ",isPullRequest", "--limit", "100")
        if err or err2 or err3:
            failed[user] = err or err2 or err3
        asks += [note(h, "review", user, side, projects, "you" if h["url"] in direct else "team")
                 for h in prs or []]
        asks += [note(h, "issue", user, side, projects) for h in issues or [] if not h.get("isPullRequest")]
    if len(failed) == len(ACCOUNTS):
        print("asks: FAIL, no account answered: %s" % "; ".join("%s: %s" % kv for kv in failed.items()),
              file=sys.stderr)
        return 1
    out = {"generated_at": datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
           "failed": failed, "asks": sorted(asks, key=lambda a: (a["since"], a["link"]))}
    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    lifecfg.write_atomic(OUT, json.dumps(out, indent=1, ensure_ascii=False) + "\n")
    counts = {}
    for a in asks:
        k = (a["account"], a["kind"] if a["kind"] == "issue" else "review-" + a["via"])
        counts[k] = counts.get(k, 0) + 1
    parts = ["%s: %d reviews for you, %d for your team, %d issues" % (
        u, counts.get((u, "review-you"), 0), counts.get((u, "review-team"), 0), counts.get((u, "issue"), 0))
        for u, _ in ACCOUNTS if u not in failed]
    parts += ["%s: FAILED (%s)" % kv for kv in failed.items()]
    print("%s; %s" % (os.path.relpath(OUT, LIFE), "; ".join(parts)))
    if "--print" in argv:
        print(open(OUT, encoding="utf-8").read(), end="")
    return 0


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