#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""GitCode Issue triage CLI (stdlib only).

Provides deterministic read/write access to GitCode v5 Issue APIs so that the
agent can gather evidence, post the fixed acknowledgement, and close an issue
in a strictly ordered, verified manner.

Commands
--------
  whoami                       Verify the token and print the authenticated user.
  list                         List issues (default state=open) for a repo.
  show <number>                Print one issue plus its comments (evidence bundle).
  dupes <number>               Print other issues whose title looks similar.
  comment <number>             Post a comment (--body / --body-file).
  close <number>               Close an issue (with a verify-then-retry chain).
  process <number>             Full flow: guard -> comment -> verify -> close -> verify.
  batch <n1,n2,...>            Run `process` for several issues sequentially.

Global options
--------------
  --owner OWNER                Repo owner (or env GITCODE_OWNER).
  --repo REPO                  Repo path  (or env GITCODE_REPO).
  --token TOKEN                Personal access token (or env GITCODE_TOKEN).
  --json                       Emit machine-readable JSON on stdout.

Exit codes
----------
  0  success
  1  unexpected/network error
  2  usage error
  3  auth error (bad or missing token)
  4  not found (issue/repo does not exist)
  5  refused by safety guard (issue must not be auto-closed)
  6  verification failed after a write (comment or close not confirmed)
"""

import argparse
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

# Windows consoles default to a legacy code page (cp936 on zh-CN), which mangles
# the Chinese titles and the fixed reply when output is piped or redirected.
# Force UTF-8 on the streams so the JSON is always readable and round-trippable.
for _stream in ("stdout", "stderr"):
    try:
        getattr(sys, _stream).reconfigure(encoding="utf-8", errors="replace")
    except (AttributeError, ValueError):
        pass

API_BASE = os.environ.get("GITCODE_API_BASE", "https://api.gitcode.com/api/v5")

# The one and only acknowledgement text used for worthless issues.
FIXED_REPLY = "感谢您的支持,欢迎进一步使用交流"

# Labels that always stop an automated close (a human must look at the issue).
GUARD_LABELS = {
    "bug", "defect", "regression", "security", "cve", "vulnerability",
    "requirement", "feature", "enhancement", "rfc", "proposal",
    "help wanted", "good first issue", "documentation", "doc",
    "priority", "critical", "blocker", "p0", "p1",
}

DEFAULT_TIMEOUT = 30


class ApiError(Exception):
    def __init__(self, status, message, payload=None):
        super().__init__(message)
        self.status = status
        self.message = message
        self.payload = payload


def die(msg, code=1):
    print("ERROR: %s" % msg, file=sys.stderr)
    sys.exit(code)


# How many times a single request is retried after an HTTP 429. Overridable via
# the GITCODE_MAX_RETRIES environment variable.
def _env_int(name, default):
    try:
        return int(os.environ.get(name, "").strip())
    except (TypeError, ValueError):
        return default


MAX_RETRIES = _env_int("GITCODE_MAX_RETRIES", 3)


# --------------------------------------------------------------------------
# Rate limiting
#
# GitCode v5 enforces a per-account+IP budget measured in requests per minute.
# Exceeding it yields HTTP 429 with a JSON body whose `error_message` reads
# "429 The number of times the user invokes this API is too large. Threshold:
# 50 times per user per Minute." A triage sweep (list + per-issue comments)
# trivially bursts past 50, so every request is retried with backoff and every
# batch run paces itself adaptively.
# --------------------------------------------------------------------------

class RateLimiter:
    """Tracks 429 pressure and enforces backoff for batch runs."""

    def __init__(self):
        self.consecutive_429 = 0
        self.total_429 = 0
        self.cooldown_until = 0.0
        self.penalty = 0.0

    def note_429(self, retry_after=None):
        self.consecutive_429 += 1
        self.total_429 += 1
        if retry_after is not None:
            wait = retry_after
        else:
            wait = min(60.0, 2.0 ** self.consecutive_429)
        self.cooldown_until = max(self.cooldown_until, time.time() + wait)
        # Pay a growing per-request penalty so the next burst is gentler.
        self.penalty = min(5.0, max(self.penalty * 2, 0.5))
        return wait

    def note_ok(self):
        self.consecutive_429 = 0
        self.penalty = 0.0

    def wait(self):
        """Sleep until any active cooldown has elapsed."""
        remaining = self.cooldown_until - time.time()
        if remaining > 0:
            time.sleep(remaining)


RATE = RateLimiter()


def _parse_retry_after(headers):
    if not headers:
        return None
    raw = headers.get("Retry-After") or headers.get("retry-after")
    if raw is None:
        return None
    try:
        return max(0.0, float(str(raw).strip()))
    except ValueError:
        return None


# --------------------------------------------------------------------------
# HTTP layer
# --------------------------------------------------------------------------

def _http(method, path, token, params=None, json_body=None, form_body=None,
          timeout=DEFAULT_TIMEOUT, max_retries=None):
    """Low-level request. Returns (status, parsed_json_or_text).

    Retries HTTP 429 with exponential backoff (honouring Retry-After when the
    server sends it) so a burst during a sweep does not surface as a hard
    failure. Other errors are raised immediately.
    """
    query = dict(params or {})
    if token:
        query["access_token"] = token
    url = "%s%s?%s" % (API_BASE, path, urllib.parse.urlencode(query))

    data = None
    headers = {"Accept": "application/json", "User-Agent": "workbuddy-gitcode-triage/1.0"}
    if json_body is not None:
        data = json.dumps(json_body).encode("utf-8")
        headers["Content-Type"] = "application/json"
    elif form_body is not None:
        data = urllib.parse.urlencode(form_body).encode("utf-8")
        headers["Content-Type"] = "application/x-www-form-urlencoded"

    retries = MAX_RETRIES if max_retries is None else max_retries
    attempt = 0
    while True:
        attempt += 1
        req = urllib.request.Request(url, data=data, headers=headers, method=method)
        retry_after = None
        try:
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                raw = resp.read().decode("utf-8", "replace")
                status = resp.status
        except urllib.error.HTTPError as e:
            raw = e.read().decode("utf-8", "replace")
            status = e.code
            retry_after = _parse_retry_after(getattr(e, "headers", None))
        except urllib.error.URLError as e:
            raise ApiError(0, "network error: %s" % e.reason)
        except TimeoutError:
            raise ApiError(0, "request timed out after %ss" % timeout)

        try:
            parsed = json.loads(raw) if raw.strip() else {}
        except ValueError:
            parsed = raw

        if status == 429 and attempt <= retries:
            wait = RATE.note_429(retry_after)
            print("rate limited (429); sleeping %.1fs then retry %d/%d"
                  % (wait, attempt, retries), file=sys.stderr)
            time.sleep(wait)
            continue

        if status >= 400:
            detail = parsed
            if isinstance(parsed, dict):
                detail = parsed.get("message") or parsed.get("error") or parsed
                if not detail or detail == parsed:
                    detail = parsed.get("error_message") or detail
            raise ApiError(status, "HTTP %s: %s" % (status, detail), parsed)
        RATE.note_ok()
        return status, parsed


def api(method, path, token, **kw):
    return _http(method, path, token, **kw)[1]


def normalize_issue(issue):
    """Canonicalise the field-name variance seen across GitCode deployments.

    Live payloads carry `assignees: []` and omit `assignee` entirely, while the
    documented shape is the opposite. Downstream code reads normalised keys only,
    so both shapes behave identically.
    """
    if not isinstance(issue, dict):
        return issue
    out = dict(issue)
    logins = extract_logins(issue, "assignee")
    out["_assignees"] = logins
    # `issue_state` is a workflow label (e.g. 待办的) and is NOT the open/closed
    # flag; `state` is. Downstream code reads `state` directly (see is_closed).
    return out


def issue_labels(issue):
    return [l.get("name", "") if isinstance(l, dict) else str(l)
            for l in (issue.get("labels") or [])]


# --------------------------------------------------------------------------
# Domain operations
# --------------------------------------------------------------------------

def get_issue(token, owner, repo, number):
    return normalize_issue(api("GET", "/repos/%s/%s/issues/%s" % (owner, repo, number), token))


CLOSED_STATES = ("closed", "close")


def is_closed(issue):
    return str(issue.get("state", "")).strip().lower() in CLOSED_STATES


def list_issues(token, owner, repo, state="open", page=1, per_page=50, labels=None, sort=None):
    params = {"state": state, "page": page, "per_page": per_page}
    if labels:
        params["labels"] = labels
    if sort:
        params["sort"] = sort
    return api("GET", "/repos/%s/%s/issues" % (owner, repo), token, params=params)


def list_comments(token, owner, repo, number, per_page=100):
    try:
        out = api(
            "GET",
            "/repos/%s/%s/issues/%s/comments" % (owner, repo, number),
            token,
            params={"per_page": per_page},
        )
    except ApiError as e:
        if e.status == 404:
            return []
        raise
    return out if isinstance(out, list) else []


def post_comment(token, owner, repo, number, body):
    payload = {"body": body}
    try:
        return api(
            "POST",
            "/repos/%s/%s/issues/%s/comments" % (owner, repo, number),
            token,
            json_body=payload,
        )
    except ApiError as e:
        # Some GitCode deployments only accept form-encoded comment bodies. Only
        # a 400 (JSON body rejected) warrants the fallback; auth/permission and
        # not-found errors must surface unchanged rather than retrying a write.
        if e.status != 400:
            raise
        return api(
            "POST",
            "/repos/%s/%s/issues/%s/comments" % (owner, repo, number),
            token,
            form_body=payload,
        )


def close_issue(token, owner, repo, number):
    """Close an issue, tolerating API path/value variance. Returns the issue JSON."""
    attempts = [
        ("/repos/%s/%s/issues/%s" % (owner, repo, number), {"state": "closed"}),
        ("/repos/%s/%s/issues/%s" % (owner, repo, number), {"state": "close"}),
        ("/repos/%s/issues/%s" % (owner, number), {"state": "closed", "repo": repo}),
    ]
    last_err = None
    for path, body in attempts:
        try:
            api("PATCH", path, token, json_body=body)
        except ApiError as e:
            last_err = e
            continue
        current = get_issue(token, owner, repo, number)
        if str(current.get("state", "")).lower() in ("closed", "close"):
            return current
    if last_err:
        raise last_err
    raise ApiError(6, "close request accepted but issue state is still open")


# --------------------------------------------------------------------------
# Evidence / classification helpers
# --------------------------------------------------------------------------

_CJK = re.compile(r"[\u4e00-\u9fff]+")
_TOKEN = re.compile(r"[A-Za-z0-9_+#.]+")


def _tokens(text):
    """Token set for similarity. Latin words plus CJK character bigrams.

    CJK has no whitespace, so whole-run tokens would only match on identical
    strings. Character bigrams give partial-overlap credit for Chinese titles,
    which is what makes duplicate detection usable on a Chinese issue tracker.
    """
    text = text or ""
    toks = set(t.lower() for t in _TOKEN.findall(text) if len(t) > 2)
    for run in _CJK.findall(text):
        if len(run) == 1:
            toks.add(run)
        else:
            for i in range(len(run) - 1):
                toks.add(run[i:i + 2])
    return toks


def _text_of(issue):
    return "%s\n%s" % (issue.get("title", ""), issue.get("body", ""))


_PRAISE_RE = re.compile(
    r"^(支持|支持一下|支持一波|支持支持|支持平台|支持开源|支持这个项目|支持华为|"
    r"支持下|支持支持一下|点赞|赞一个|很棒|很好|挺好的|很好的项目|不错的项目|"
    r"不错|加油|好好好|好好好好|混一下|混个|来做个任务|做任务|完成任务|打扰了|"
    r"谢谢|感谢|顶|mark|thanks?|thank you|nice|good|great|lgtm|ok|okay)$"
)
_PRAISE_LOOP_RE = re.compile(
    r"^(支持|赞|好|顶|混|谢谢|感谢|thanks?|nice|good|ok)"
    r"([~!!。.,,、\s]*\1)*[~!!。.,,、\s]*$"
)

# Vocabulary used to test whether a short post is composed *entirely* of
# courtesy/praise filler. Longest entries first so greedy removal works.
_PRAISE_VOCAB = [
    "支持一下", "支持一波", "支持支持", "支持平台", "支持开源", "支持华为",
    "支持下", "支持这个项目", "向大佬学习", "来做个任务", "完成任务",
    "很好的项目", "不错的项目", "挺好的项目", "打扰了", "感谢开发团队",
    "期待更新", "我也来", "我也", "也不白来", "留个star",
    "支持", "一下", "一波", "点赞", "赞一个", "很棒", "很好", "挺好", "不错",
    "加油", "好", "赞", "顶", "混", "谢谢", "感谢", "关注", "项目", "大佬",
    "学习", "开源", "平台", "华为", "哈哈", "哈哈哈", "哈", "啦", "了", "的",
    "这个", "很", "个", "也", "来",
    "thanks", "thank", "you", "nice", "good", "great", "lgtm", "mark", "ok",
]
_PRAISE_CORE = re.compile(r"(支持|点赞|赞|加油|谢谢|感谢|顶|混|好|很棒|很好|不错)")

# Point / reward farming: the post exists only to satisfy a contribution-task
# rule. Always paired with reward vocabulary so a real points feature request
# ("建议积分可兑换") is not swept up.
_POINTS_TASK_RE = re.compile(r"积分|赚分|刷分|打卡|签到|任务")
_POINTS_ACT_RE = re.compile(r"拿|攒|赚|刷|领|得|完不成|完成不了|发|混")
_REWARD_ONLY_RE = re.compile(r"^[拿来攒赚刷领得个积分啊呀吗?!?。.,,\s]*$")

# Labels that support a worthless verdict when the text also looks like noise.
JUNK_LABELS = {"invalid", "spam", "wontfix", "duplicate", "invalid-issue"}


def _consume_praise(text, vocab):
    """Greedily strip praise vocabulary and filler; True if nothing substantive remains."""
    rest = re.sub(r"[\d\W_]+", "", text or "")
    changed = True
    while changed and rest:
        changed = False
        for v in vocab:
            if rest.startswith(v):
                rest = rest[len(v):]
                changed = True
                break
    return rest == ""


def _count_run(stripped, ch):
    """Longest run of a single character."""
    best = cur = 0
    for c in stripped:
        if c == ch:
            cur += 1
            best = max(best, cur)
        else:
            cur = 0
    return best


def _is_repetitive(text, min_repeat=2):
    """True when a short phrase is simply repeated, e.g.
    '拿个积分拿个积分' or '为什么呢?为什么呢?为什么呢?'. Not for long posts."""
    if not text or len(text) > 60:
        return False
    for size in range(2, max(3, len(text) // 2) + 1):
        unit = text[:size]
        if len(unit) * min_repeat <= len(text) and text == unit * (len(text) // size):
            return True
    return False


def _is_praise_junk(stripped, title_only=None):
    """Detect courtesy/praise-only or task-farming posts that carry no request.

    Observed heavily on GitCode community repos: 支持一下 / 支持一波 / 支持开源 /
    支持平台 / 很好的项目 / 挺好的项目支持支持一下 / 混一下 / 来做任务的 /
    好好好好好好好. These fill the tracker without asking for anything, so the
    rubric treats them as worthless. Returns (matched, signal_name).
    """
    text = stripped or ""
    if not text:
        return False, None
    # Courtesy word repeated: 支持一下支持一下支持一下 / 支持支持支持
    if _PRAISE_LOOP_RE.match(text):
        return True, "praise_loop"
    # Any character run of 6+ that dominates the string: 好好好好好好好好好
    for ch in set(text):
        if _count_run(text, ch) >= 6 and text.count(ch) >= max(6, len(text) - 4):
            return True, "repeated_single_char"
    # Pure courtesy phrase.
    if _PRAISE_RE.match(text):
        return True, "praise_only"
    # Sentence assembled only from courtesy morphemes.
    core = re.sub(r"[~!!。.,,、\s]", "", text)
    if core and re.fullmatch(r"(支持|赞|好|顶|谢谢|感谢|加油)+", core):
        return True, "praise_loop"
    # Short post made up entirely of praise vocabulary, e.g.
    # 挺好的项目支持支持一下 / 支持一下支持一下支持一下
    if len(core) <= 40 and _PRAISE_CORE.search(core) and _consume_praise(core, _PRAISE_VOCAB):
        return True, "praise_only"
    # Reward/point farming: short posts that exist only to satisfy a
    # contribution task. The length cap keeps a genuine
    # "建议在活动模块增加积分兑换说明" out of this branch.
    if len(text) <= 60 and _POINTS_TASK_RE.search(text) and (
            _POINTS_ACT_RE.search(text) or _REWARD_ONLY_RE.match(text)
            or text.count("积分") + text.count("任务") >= 2
            or _is_repetitive(text)):
        return True, "points_farming"
    # Title is courtesy filler and the body adds nothing new.
    if title_only:
        t = re.sub(r"[\d\W_]+", "", title_only)
        if t and len(t) <= 20 and _PRAISE_CORE.search(t) and _consume_praise(t, _PRAISE_VOCAB):
            return True, "praise_only"
    return False, None


def classify(issue, comments):
    """Produce a non-binding heuristic report to support the agent's judgement.

    This NEVER decides by itself and never triggers a write. It only surfaces
    the signals named in references/triage-rubric.md so the agent can reason.
    """
    text = _text_of(issue)
    stripped = re.sub(r"\s+", "", text)
    body = issue.get("body") or ""
    body_stripped = re.sub(r"\s+", "", body)
    body_len = len(body_stripped)
    cjk = len(_CJK.findall(text))
    title = (issue.get("title") or "").strip()
    labels = [l.get("name", "") if isinstance(l, dict) else str(l)
              for l in (issue.get("labels") or [])]

    signals = []
    if body_len <= 8 and len(title) <= 8:
        signals.append("empty_or_tiny_body")
    if re.fullmatch(r"[\W\d_]*", stripped or ""):
        signals.append("no_words_at_all")
    if re.fullmatch(r"(.)\1{4,}", stripped or ""):
        signals.append("repeated_single_char")

    # A maintainer already marked this as junk — strong supporting evidence.
    if set(x.lower() for x in labels) & JUNK_LABELS:
        signals.append("maintainer_marked_junk")

    # Test/placeholder posts: 测试 / issueTest / test / 来测试一下
    if re.fullmatch(r"(issue)?\s*(test|测试|try|demo|hello)\d*", stripped or "", re.I) \
            or re.search(r"(来)?(测试|试)一下", stripped or "") \
            or re.fullmatch(r"(issue)?\s*test", title, re.I):
        signals.append("placeholder_title")

    # Praise / courtesy / task-farming posts (dominant junk class on GitCode).
    matched, praise_sig = _is_praise_junk(stripped, title)
    if matched:
        if praise_sig not in signals:
            signals.append(praise_sig)

    if re.search(r"^\s*(test|测试|test\s*only|asdf|aaa+|111+|\?+)\s*$", title, re.I):
        signals.append("placeholder_title")
    if not cjk and re.search(r"^[\x00-\x7f]+$", stripped or "") and body_len < 20:
        signals.append("short_latin_only")
    if re.search(r"(怎么安装|如何安装|安装教程|how\s+to\s+install|求教程|新手|源码在哪|下载地址)", text, re.I):
        signals.append("generic_usage_question")
    if re.search(r"(微信|qq|电话|手机号|加我|私聊|合作|广告|推广|招聘|兼职|qq群)", text, re.I):
        signals.append("off_topic_or_promotion")
    if re.search(r"(^|\n)\s*(https?://\S+)\s*($|\n)", text) and body_len < 40:
        signals.append("link_only")
    # Task-farming tell: the reporter announces they are only here for a task.
    if re.search(r"(做任务|完成任务|不用理我|自己关issue|来做个任务|打扰了)", text):
        signals.append("task_farming")

    # A genuine request must never be reported as junk. When request-shaped
    # language is present, the length/repetition signals are noise, not evidence.
    legit = legit_request_reasons(text)
    if legit:
        drop = {"empty_or_tiny_body", "no_words_at_all", "short_latin_only",
                "praise_only", "praise_loop", "repeated_single_char",
                "placeholder_title", "task_farming"}
        signals = [s for s in signals if s not in drop]
        signals.append("legit_request:%s" % ",".join(legit))

    comment_authors = set()
    for c in comments:
        u = c.get("user") or {}
        if u.get("login"):
            comment_authors.add(u["login"])
    signals.append("has_comments:%d" % len(comments))

    return {
        "number": issue.get("number"),
        "title": title,
        "state": issue.get("state"),
        "author": (issue.get("user") or {}).get("login"),
        "labels": labels,
        "body_length": body_len,
        "comment_count": len(comments),
        "comment_authors": sorted(comment_authors),
        "heuristic_signals": signals,
        "guard_labels_present": sorted(set(l.lower() for l in labels) & GUARD_LABELS),
    }


def similarity(a, b):
    ta, tb = _tokens(a), _tokens(b)
    if not ta or not tb:
        return 0.0
    return len(ta & tb) / float(len(ta | tb))


def find_dupes(token, owner, repo, issue, limit=5, threshold=0.5):
    title = issue.get("title") or ""
    try:
        # Walk every page: a single page silently truncates a tracker of >100
        # issues, which would hide duplicates living past the first page.
        others = []
        page = 1
        while True:
            batch = list_issues(token, owner, repo, state="all",
                                page=page, per_page=100)
            if not isinstance(batch, list):
                batch = (batch or {}).get("issues", []) if isinstance(batch, dict) else []
            if not batch:
                break
            others.extend(o for o in batch if isinstance(o, dict))
            if len(batch) < 100:
                break
            page += 1
            RATE.wait()
    except ApiError:
        return []
    scored = []
    for o in others:
        if not isinstance(o, dict):
            continue
        if str(o.get("number")) == str(issue.get("number")):
            continue
        s = similarity(title, o.get("title") or "")
        if s >= threshold:
            scored.append({"number": o.get("number"), "title": o.get("title"),
                           "state": o.get("state"), "score": round(s, 3)})
    scored.sort(key=lambda x: x["score"], reverse=True)
    return scored[:limit]


def extract_logins(issue, key):
    """Collect logins from a field that may be a list of strings, list of dicts,
    or a single dict/string. GitCode is inconsistent here: some responses carry
    `assignees: []`, others `assignee: {...}` or a bare login string."""
    raw = issue.get(key)
    out = []
    if not raw:
        extra = issue.get(key + "s")
        raw = extra
    if not raw:
        return out
    if not isinstance(raw, list):
        raw = [raw]
    for item in raw:
        if isinstance(item, str):
            out.append(item)
        elif isinstance(item, dict):
            for k in ("login", "name", "username"):
                if item.get(k):
                    out.append(item[k])
                    break
    return [x for x in out if x]


def is_bot(login, extra_bots=()):
    """Heuristic bot detection. GitCode project bots commonly end in _bot
    (e.g. grape_bot) or are flagged as Bot accounts."""
    if not login:
        return False
    low = login.lower()
    if low in set(b.lower() for b in extra_bots):
        return True
    return low.endswith("_bot") or low.endswith("-bot") or low.endswith("[bot]")


# Veto patterns: text that marks a post as a genuine request rather than noise.
# A terse legit question ("是否支持 docker 部署") is short, but it IS a real
# enquiry about the project — closing it silently would be wrong.
_LEGIT_PATTERNS = [
    # Domain vocabulary: the post is about what this kind of project actually does.
    ("domain_substance",
     r"部署|配置|安装|运行|用法|参数|字段|接口|api|文档|示例|脚本|输出|导出|导入|"
     r"预算|风险|宣传|方案|模板|依赖|版本|兼容|性能|报错|异常|日志|测试|单元测试|"
     r"回归|路径|目录|编码|安全|证书|权限|并发|缓存|校验|格式|"
     r"docker|kubernetes|k8s|node|python|chromium|playwright|schema|"
     r"workflow|agent|prompt|token|model|llm"),
    ("project_question",
     r"是否支持|能否支持|可以支持|支持不支持|能不能|可否|是否考虑|有没有计划|"
     r"如何(配置|使用|部署|安装|运行)|怎么(配置|部署|运行)|请问|求解答|"
     r"do you support|is there (a|any)|can (it|you)|how (do|can|to) i"),
    ("references_project_artifact",
     r"\.(py|sh|js|ts|json|ya?ml|md|txt|toml|cfg|ini)\b|"
     r"README|SKILL\.md|config\.json|config\.yaml|requirements\.txt|"
     r"dockerfile|docker-compose|gen_[a-z_]+\.py|skills/|scripts/"),
    ("defect_or_requirement_language",
     r"建议|需求|希望|期望|增加|新增|添加|扩展|补[充齐]|修复|修一下|报错|异常|失败|"
     r"崩溃|复现|无法|不能|缺[少失]|不一致|不正确|不生效|没有生效|硬编码|会导致|"
     r"风险|安全|"
     r"\bbug\b|\bfix\b|error|exception|traceback|crash|regression|fail"),
    # Hypothetical phrasing that marks a wish as a placeholder (拿不动码).
    ("hypothetical_wish",
     r"如果能|要是能|如果可以|如果能支持|希望(能|可以)?支持|就好了|就好了吧|"
     r"支持.{0,6}就好了"),
]

# A complaint about the platform's reward mechanics is noise; it must not be
# rescued by generic "defect language" such as 完不成 / 拿不到.
_VETO_EXEMPT_PATTERNS = [
    "defect_or_requirement_language", "hypothetical_wish", "project_question",
]


def legit_request_reasons(text):
    """Return veto reasons indicating the text carries a real, project-relevant ask.

    Requires domain substance OR a project artifact reference, so a bare wish
    ("要是能用就好了") or a reward complaint does not count as a real request.
    """
    text = text or ""
    found = {}
    for name, pat in _LEGIT_PATTERNS:
        if re.search(pat, text, re.I):
            found[name] = True

    # Reward/point chatter is not a legitimate project request. A substantive
    # technical suggestion is exempt (domain vocabulary or an artifact reference).
    if _POINTS_TASK_RE.search(text) and not (
            found.get("domain_substance") or found.get("references_project_artifact")):
        if (_POINTS_ACT_RE.search(text)
                or _REWARD_ONLY_RE.match(re.sub(r"\s+", "", text))):
            return []

    reasons = []
    if found.get("domain_substance") or found.get("references_project_artifact"):
        reasons.extend(k for k in found
                       if k in ("domain_substance", "references_project_artifact"))
        if found.get("defect_or_requirement_language") and found.get("domain_substance"):
            reasons.append("defect_or_requirement_language")
        elif found.get("project_question") and found.get("domain_substance"):
            reasons.append("project_question")
    # A clear project question always counts, even without extra vocabulary.
    if found.get("project_question"):
        reasons.append("project_question")
    return sorted(set(reasons))


def safety_guard(issue, comments, agent_login=None, bot_logins=(), ignore_bots=True):
    """Return (allowed: bool, reasons: list[str]). A False result must abort.

    Note on `assignee` vs `assignees`: the live GitCode v5 issue payload carries
    `assignees` (a list) and often omits `assignee` entirely, so both are read.
    Likewise `milestone` may be absent from the payload; a missing field is
    treated as "no milestone" rather than crashing.
    """
    reasons = []
    labels = issue_labels(issue)
    hit = sorted(set(x.lower() for x in labels) & GUARD_LABELS)
    if hit:
        reasons.append("guard_label: %s" % ", ".join(hit))

    assignees = issue.get("_assignees")
    if assignees is None:
        assignees = extract_logins(issue, "assignee")
    if assignees and not (ignore_bots and all(is_bot(a, bot_logins) for a in assignees)):
        reasons.append("issue_is_assigned: %s" % ", ".join(assignees))

    if issue.get("milestone"):
        reasons.append("issue_has_milestone")

    # The body may be terse yet still be a legitimate enquiry. Any request-shaped
    # language vetoes the close regardless of length.
    for r in legit_request_reasons(_text_of(issue)):
        reasons.append("legit_request: %s" % r)

    # Substantive discussion: a reporter-external participant replied. Bot
    # comments (project automation) are excluded from this check, otherwise the
    # mere presence of a CI/QA bot would block every close.
    author = (issue.get("user") or {}).get("login")
    for c in comments:
        login = (c.get("user") or {}).get("login")
        if not login or login in (author, agent_login):
            continue
        if ignore_bots and is_bot(login, bot_logins):
            continue
        reasons.append("external_participant: %s" % login)
        break
    return (not reasons), reasons


def already_acknowledged(comments, agent_login=None, phrase=FIXED_REPLY):
    for c in comments:
        body = (c.get("body") or "").strip()
        login = (c.get("user") or {}).get("login")
        if agent_login and login != agent_login:
            continue
        if phrase and body == phrase.strip():
            return True
    return False


# --------------------------------------------------------------------------
# Output helpers
# --------------------------------------------------------------------------

def emit(payload, as_json=None):
    # Output is always machine-readable JSON; `as_json` / `--json` is a no-op
    # retained for CLI compatibility.
    print(json.dumps(payload, ensure_ascii=False, indent=2))


def resolve_ctx(args, require_token=True, require_repo=True):
    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")
    if require_repo and (not owner or not repo):
        die("missing --owner/--repo (or GITCODE_OWNER / GITCODE_REPO)", 2)
    if require_token and not token:
        die("missing --token (or GITCODE_TOKEN). Read-only recon can run without a "
            "token via `--no-auth` on commands that support it.", 2)
    # A token without --agent-login silently weakens two safety properties: the
    # idempotency check cannot tell the agent's own earlier reply apart from a
    # stranger's, and the agent's own comment can be read as external
    # participation and veto every close. Warn loudly rather than fail, so
    # dry-run / read-only use stays frictionless.
    agent_login = getattr(args, "agent_login", None)
    if token and not agent_login and getattr(args, "cmd", "") in ("process", "batch", "close", "comment"):
        print("WARNING: --agent-login is not set. Without the token owner's login "
              "(not their display name), idempotency and the external-participant "
              "guard are unreliable. Run `whoami` and pass its `login` value.",
              file=sys.stderr)
    return token, owner, repo


def call_or_die(fn, *a, **kw):
    try:
        return fn(*a, **kw)
    except ApiError as e:
        if e.status in (401, 403):
            die("authentication failed (%s). Check the token and its scopes." % e.message, 3)
        if e.status == 404:
            die("not found: %s" % e.message, 4)
        die(str(e.message), 1)


# --------------------------------------------------------------------------
# Commands
# --------------------------------------------------------------------------

def cmd_whoami(args):
    token, owner, repo = resolve_ctx(
        args, require_token=not getattr(args, "no_auth", False), require_repo=False)
    user = call_or_die(api, "GET", "/user", token)
    login = user.get("login")
    payload = {"login": login, "name": user.get("name")}
    # If an agent login was supplied, verify it matches the token owner. A
    # mismatch (e.g. the display name was passed instead of the login) silently
    # disables idempotency and the participant guard, so say so explicitly.
    supplied = getattr(args, "agent_login", None)
    if supplied:
        payload["agent_login_matches"] = (supplied == login)
        if supplied != login:
            payload["agent_login_warning"] = (
                "--agent-login %r does not match the token owner %r. Use the "
                "`login` value, not the display name (`name` = %r)."
                % (supplied, login, user.get("name")))
    emit(payload, args.json)
    return 0


def cmd_list(args):
    token, owner, repo = resolve_ctx(args, require_token=not getattr(args, "no_auth", False))
    per_page = args.per_page
    pages = 10 ** 6 if getattr(args, "all_pages", False) else args.pages
    issues = []
    page = args.page
    seen = set()
    for _ in range(max(1, pages)):
        batch = call_or_die(list_issues, token, owner, repo, state=args.state,
                            page=page, per_page=per_page)
        if not isinstance(batch, list):
            batch = (batch or {}).get("issues", []) if isinstance(batch, dict) else []
        if not batch:
            break
        for i in batch:
            if not isinstance(i, dict):
                continue
            n = i.get("number")
            if n in seen:
                continue
            seen.add(n)
            issues.append(i)
        # A short page means the last page has been reached.
        if len(batch) < per_page:
            break
        page += 1
        RATE.wait()
    rows = [{
        "number": i.get("number"),
        "state": i.get("state"),
        "title": i.get("title"),
        "author": (i.get("user") or {}).get("login"),
        "labels": [l.get("name") if isinstance(l, dict) else l for l in (i.get("labels") or [])],
        "comments": i.get("comments"),
        "created_at": i.get("created_at"),
    } for i in issues if isinstance(i, dict)]
    emit({"count": len(rows), "issues": rows}, args.json)
    return 0


def cmd_show(args):
    token, owner, repo = resolve_ctx(args, require_token=not getattr(args, "no_auth", False))
    issue = call_or_die(get_issue, token, owner, repo, args.number)
    comments = call_or_die(list_comments, token, owner, repo, args.number)
    report = classify(issue, comments)
    report["body"] = issue.get("body")
    report["dupes"] = call_or_die(find_dupes, token, owner, repo, issue)
    report["comments"] = [{
        "id": c.get("id"),
        "author": (c.get("user") or {}).get("login"),
        "body": c.get("body"),
    } for c in comments]
    allowed, reasons = safety_guard(issue, comments, args.agent_login,
                                    bot_logins=args.bot_logins,
                                    ignore_bots=not args.count_bots)
    report["guard_allowed"] = allowed
    report["guard_reasons"] = reasons
    report["bot_commenters"] = sorted({
        (c.get("user") or {}).get("login") for c in comments
        if is_bot((c.get("user") or {}).get("login"), args.bot_logins)
    })
    emit(report, args.json)
    return 0


def cmd_dupes(args):
    token, owner, repo = resolve_ctx(args, require_token=not getattr(args, "no_auth", False))
    issue = call_or_die(get_issue, token, owner, repo, args.number)
    emit({"number": issue.get("number"), "dupes": call_or_die(
        find_dupes, token, owner, repo, issue, threshold=args.threshold)}, args.json)
    return 0


def _read_body(args):
    if args.body_file:
        with open(args.body_file, "r", encoding="utf-8") as fh:
            return fh.read()
    return args.body if args.body is not None else FIXED_REPLY


def cmd_comment(args):
    token, owner, repo = resolve_ctx(args)
    body = _read_body(args)
    resp = call_or_die(post_comment, token, owner, repo, args.number, body)
    comments = call_or_die(list_comments, token, owner, repo, args.number)
    if not any((c.get("body") or "").strip() == body.strip() for c in comments):
        die("comment POST returned but the comment was not found on the issue", 6)
    emit({"posted": True, "comment_id": (resp or {}).get("id"), "body": body}, args.json)
    return 0


def cmd_close(args):
    token, owner, repo = resolve_ctx(args)
    issue = call_or_die(get_issue, token, owner, repo, args.number)
    if is_closed(issue):
        emit({"closed": True, "already_closed": True, "number": args.number}, args.json)
        return 0
    updated = call_or_die(close_issue, token, owner, repo, args.number)
    emit({"closed": is_closed(updated), "state": updated.get("state"),
          "number": args.number}, args.json)
    return 0


def _process_one(token, owner, repo, number, dry_run, agent_login, phrase, force,
                 bot_logins=(), count_bots=False):
    """Ordered, verified single-issue flow. Returns a result dict."""
    result = {"number": number, "action": None, "ok": False, "detail": None}
    issue = get_issue(token, owner, repo, number)
    if is_closed(issue):
        result.update(action="skip", ok=True, detail="already_closed")
        return result

    comments = list_comments(token, owner, repo, number)
    allowed, reasons = safety_guard(issue, comments, agent_login,
                                    bot_logins=bot_logins,
                                    ignore_bots=not count_bots)

    if already_acknowledged(comments, agent_login, phrase):
        # Already replied; only the close step remains.
        if not allowed and not force:
            result.update(action="refused", detail={"guard": reasons})
            return result
        if dry_run:
            result.update(action="close_only(dry-run)", ok=True, detail="reply_present")
            return result
        close_issue(token, owner, repo, number)
        result.update(action="closed", ok=True, detail="reply_already_present")
        return result

    if not allowed and not force:
        result.update(action="refused", detail={"guard": reasons})
        return result

    if dry_run:
        result.update(action="reply+close(dry-run)", ok=True,
                      detail={"would_reply": phrase})
        return result

    # STRICT ORDER: reply first, verify it landed, only then close.
    post_comment(token, owner, repo, number, phrase)
    after = list_comments(token, owner, repo, number)
    if not any((c.get("body") or "").strip() == phrase.strip() for c in after):
        raise ApiError(6, "reply not confirmed; aborting before close")
    close_issue(token, owner, repo, number)
    final = get_issue(token, owner, repo, number)
    closed = is_closed(final)
    result.update(action="closed", ok=closed,
                  detail="reply+close verified" if closed else "close unverified")
    return result


def cmd_process(args):
    token, owner, repo = resolve_ctx(args)
    try:
        result = _process_one(token, owner, repo, args.number, args.dry_run,
                              args.agent_login, args.phrase, args.force,
                              bot_logins=args.bot_logins,
                              count_bots=args.count_bots)
    except ApiError as e:
        if e.status in (401, 403):
            die("authentication failed: %s" % e.message, 3)
        if e.status == 404:
            die("not found: %s" % e.message, 4)
        if e.status == 6:
            die(str(e.message), 6)
        die(str(e.message), 1)
    emit(result, args.json)
    if result["action"] == "refused":
        return 5
    if not result["ok"]:
        return 6
    return 0


def cmd_batch(args):
    token, owner, repo = resolve_ctx(args)
    numbers = [n.strip() for n in str(args.numbers).split(",") if n.strip()]
    if not numbers:
        die("no issue numbers supplied", 2)
    results = []
    for n in numbers:
        RATE.wait()
        try:
            results.append(_process_one(token, owner, repo, n, args.dry_run,
                                        args.agent_login, args.phrase, args.force,
                                        bot_logins=args.bot_logins,
                                        count_bots=args.count_bots))
        except ApiError as e:
            results.append({"number": n, "action": "error", "ok": False,
                            "detail": str(e.message)})
        if len(numbers) > 1:
            # Base delay plus any penalty accrued from recent 429s.
            time.sleep(args.delay + RATE.penalty)
    emit({"processed": len(results), "rate_limited": RATE.total_429,
          "results": results}, args.json)
    bad = [r for r in results if not r.get("ok")]
    return 0 if not bad else (5 if any(r["action"] == "refused" for r in bad) else 6)


# --------------------------------------------------------------------------
# Parser
# --------------------------------------------------------------------------

def build_parser():
    p = argparse.ArgumentParser(prog="gitcode_issue", description="GitCode Issue triage CLI")
    p.add_argument("--owner")
    p.add_argument("--repo")
    p.add_argument("--token")
    p.add_argument("--json", action="store_true", help="JSON output (always on; kept for clarity)")
    p.add_argument("--agent-login", default=os.environ.get("GITCODE_AGENT_LOGIN"),
                   help="login used by the agent account, for idempotency + guard checks")
    p.add_argument("--bot-logins", default=os.environ.get("GITCODE_BOT_LOGINS", ""),
                   help="comma-separated extra bot logins to ignore in the participant guard")
    p.add_argument("--count-bots", action="store_true",
                   help="treat bot comments as external participants (strictest mode)")
    p.add_argument("--no-auth", action="store_true",
                   help="read-only access without a token (list/show/dupes only)")
    sub = p.add_subparsers(dest="cmd", required=True)

    sub.add_parser("whoami")

    sp = sub.add_parser("list")
    sp.add_argument("--state", default="open", choices=["open", "closed", "all"])
    sp.add_argument("--page", type=int, default=1)
    sp.add_argument("--per-page", type=int, default=50)
    sp.add_argument("--pages", type=int, default=1,
                    help="how many pages to fetch starting at --page (default 1)")
    sp.add_argument("--all", dest="all_pages", action="store_true",
                    help="fetch every page until the tracker is exhausted")
    sp.add_argument("--no-auth", action="store_true", help="skip the token requirement")
    sp.set_defaults(func=cmd_list)

    sp = sub.add_parser("show")
    sp.add_argument("number")
    sp.add_argument("--no-auth", action="store_true", help="skip the token requirement")
    sp.set_defaults(func=cmd_show)

    sp = sub.add_parser("dupes")
    sp.add_argument("number")
    sp.add_argument("--threshold", type=float, default=0.5)
    sp.add_argument("--no-auth", action="store_true", help="skip the token requirement")
    sp.set_defaults(func=cmd_dupes)

    sp = sub.add_parser("comment")
    sp.add_argument("number")
    sp.add_argument("--body")
    sp.add_argument("--body-file")
    sp.set_defaults(func=cmd_comment)

    sp = sub.add_parser("close")
    sp.add_argument("number")
    sp.set_defaults(func=cmd_close)

    sp = sub.add_parser("process")
    sp.add_argument("number")
    sp.add_argument("--dry-run", action="store_true")
    sp.add_argument("--force", action="store_true", help="override the safety guard (human decision)")
    sp.add_argument("--phrase", default=FIXED_REPLY)
    sp.set_defaults(func=cmd_process)

    sp = sub.add_parser("batch")
    sp.add_argument("numbers", help="comma-separated issue numbers")
    sp.add_argument("--dry-run", action="store_true")
    sp.add_argument("--force", action="store_true")
    sp.add_argument("--phrase", default=FIXED_REPLY)
    sp.add_argument("--delay", type=float, default=1.0)
    sp.set_defaults(func=cmd_batch)

    # whoami has no extra args
    return p


def main(argv=None):
    parser = build_parser()
    args = parser.parse_args(argv)
    if args.cmd == "whoami":
        return cmd_whoami(args)
    return args.func(args)


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