# -*- coding: utf-8 -*-
"""Read-only triage sweep: classify every issue in one pass.

Why this exists
---------------
Running `show` once per issue costs three API calls each (issue, comments,
dupes) and prints pages of JSON. A tracker of a few hundred issues blows the
50-requests-per-minute budget and is unreadable. This script instead imports the
CLI as a library, walks `list --all`, fetches comments only for issues that
actually have them, and calls the module's own `classify()` + `safety_guard()`
so the verdicts are identical to the CLI's.

It makes **no writes** — every request is a GET.

Usage
-----
    python sweep.py --owner <owner> --repo <repo> [--token <t>] [--json]
                    [--state all] [--agent-login <login>] [--out report.md]

Public repositories need no token; pass --no-auth (default when --token is
absent) to be explicit.

Output
------
A table, one row per issue: number, state, verdict, signals, title. Verdict is
one of:
    CLOSE   a strong junk signal is present AND the safety guard allows a close
    KEEP    the guard vetoes (legit request, guard label, assigned, discussion)
    HUMAN   junk signals are weak/ambiguous — decide by reading the body
"""

import argparse
import importlib.util
import io
import json
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))


def load_cli():
    """Import gitcode_issue.py next to this file as a module (no install)."""
    path = os.path.join(HERE, "gitcode_issue.py")
    spec = importlib.util.spec_from_file_location("gitcode_issue", path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


# Strong junk signals: presence of any of these, plus an allowing guard, means
# the issue is a safe close candidate. Mirrors references/triage-rubric.md.
STRONG = {
    "empty_or_tiny_body", "no_words_at_all", "repeated_single_char",
    "placeholder_title", "short_latin_only", "generic_usage_question",
    "off_topic_or_promotion", "link_only",
    "praise_only", "praise_loop", "points_farming", "task_farming",
    "maintainer_marked_junk",
}


def verdict_for(cls, allowed, reasons):
    """Turn signals + guard verdict into CLOSE / KEEP / HUMAN."""
    sigs = set(cls.get("heuristic_signals") or [])
    if not allowed:
        return "KEEP", reasons
    if sigs & STRONG:
        return "CLOSE", []
    return "HUMAN", []


def main(argv=None):
    p = argparse.ArgumentParser(description="Read-only GitCode issue triage sweep")
    p.add_argument("--owner")
    p.add_argument("--repo")
    p.add_argument("--token")
    p.add_argument("--agent-login")
    p.add_argument("--bot-logins", default=os.environ.get("GITCODE_BOT_LOGINS", ""))
    p.add_argument("--state", default="all", choices=["open", "closed", "all"])
    p.add_argument("--per-page", type=int, default=50)
    p.add_argument("--json", action="store_true", help="emit JSON instead of a table")
    p.add_argument("--out", help="also write the report to this file")
    p.add_argument("--no-auth", action="store_true")
    p.add_argument("--max", type=int, default=0,
                   help="stop after N issues (0 = all); useful for a trial run")
    args = p.parse_args(argv)

    gi = load_cli()

    owner = args.owner or os.environ.get("GITCODE_OWNER")
    repo = args.repo or os.environ.get("GITCODE_REPO")
    token = args.token or os.environ.get("GITCODE_TOKEN") or ""
    if not owner or not repo:
        print("ERROR: --owner/--repo (or GITCODE_OWNER / GITCODE_REPO) required",
              file=sys.stderr)
        return 2

    bot_logins = tuple(x.strip() for x in args.bot_logins.split(",") if x.strip())

    # --- walk every page -------------------------------------------------
    issues = []
    page = 1
    while True:
        batch = gi.list_issues(token, owner, repo, state=args.state,
                               page=page, per_page=args.per_page)
        page += 1
        if not isinstance(batch, list):
            batch = (batch or {}).get("issues", []) if isinstance(batch, dict) else []
        if not batch:
            break
        issues.extend(i for i in batch if isinstance(i, dict))
        if len(batch) < args.per_page:
            break
        gi.RATE.wait()

    if args.max:
        issues = issues[:args.max]

    rows = []
    for i, issue in enumerate(issues, 1):
        num = issue.get("number")
        # Only fetch comments when the count says there are some: on a large
        # tracker most issues have none, and skipping them saves most of the
        # request budget.
        comments = []
        if issue.get("comments"):
            try:
                comments = gi.list_comments(token, owner, repo, num)
            except gi.ApiError as e:
                comments = []
                print("WARN: comments for #%s failed: HTTP %s" % (num, e.status),
                      file=sys.stderr)
            gi.RATE.wait()
        cls = gi.classify(issue, comments)
        allowed, reasons = gi.safety_guard(
            issue, comments, args.agent_login, bot_logins=bot_logins)
        v, why = verdict_for(cls, allowed, reasons)
        rows.append({
            "number": num,
            "state": issue.get("state"),
            "verdict": v,
            "verdict_reasons": why,
            "signals": cls["heuristic_signals"],
            "guard_allowed": allowed,
            "title": cls["title"],
            "author": cls["author"],
            "labels": cls["labels"],
        })
        if not args.json:
            print("[%3d/%3d] #%-5s %-5s %-6s %s"
                  % (i, len(issues), num, v, "ok" if allowed else "veto",
                     (cls["title"] or "")[:48]), file=sys.stderr)

    summary = {
        "owner": owner,
        "repo": repo,
        "state": args.state,
        "total": len(rows),
        "close": sum(1 for r in rows if r["verdict"] == "CLOSE"),
        "keep": sum(1 for r in rows if r["verdict"] == "KEEP"),
        "human": sum(1 for r in rows if r["verdict"] == "HUMAN"),
        "rows": rows,
    }

    if args.json:
        text = json.dumps(summary, ensure_ascii=False, indent=2)
    else:
        lines = []
        lines.append("GitCode triage sweep — %s/%s (state=%s)" % (owner, repo, args.state))
        lines.append("total=%d  CLOSE=%d  KEEP=%d  HUMAN=%d"
                     % (summary["total"], summary["close"], summary["keep"], summary["human"]))
        lines.append("")
        lines.append("%-7s %-6s %-8s %s" % ("issue", "state", "verdict", "title / signals"))
        lines.append("-" * 100)
        for r in rows:
            sig = ",".join(s for s in r["signals"] if not s.startswith("has_comments:"))
            lines.append("#%-6s %-6s %-8s %s" % (r["number"], r["state"], r["verdict"],
                                                  (r["title"] or "")[:56]))
            detail = sig or "-"
            if r["verdict_reasons"]:
                detail += "  | guard: " + "; ".join(r["verdict_reasons"])
            lines.append("        %s" % detail)
        text = "\n".join(lines)

    print(text)
    if args.out:
        # always write UTF-8 so a Windows console redirect cannot mangle it
        with io.open(args.out, "w", encoding="utf-8") as fh:
            fh.write(text)

    # Close candidates are the actionable output.
    return 0


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