# -*- coding: utf-8 -*-
"""Offline self-test: exercise the pure logic and the ordered flow with a fake HTTP layer."""
import importlib.util
import json
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("gi", os.path.join(HERE, "gitcode_issue.py"))
gi = importlib.util.module_from_spec(spec)
spec.loader.exec_module(gi)

fails = []


def check(name, cond):
    print(("PASS  " if cond else "FAIL  ") + name)
    if not cond:
        fails.append(name)


# ---- fixtures -------------------------------------------------------------
def issue(number=1, title="", body="", labels=None, assignee=None, milestone=None,
          state="open", login="reporter"):
    return {"number": number, "title": title, "body": body, "state": state,
            "labels": [{"name": x} for x in (labels or [])],
            "assignee": assignee, "milestone": milestone,
            "user": {"login": login}}


def comment(body, login="reporter"):
    return {"id": 1, "body": body, "user": {"login": login}}


# ---- classify / signals ---------------------------------------------------
r = gi.classify(issue(title="111", body="11111111"), [])
check("empty_or_tiny_body", "empty_or_tiny_body" in r["heuristic_signals"])
check("repeated_single_char", "repeated_single_char" in r["heuristic_signals"])
check("placeholder_title", "placeholder_title" in r["heuristic_signals"])

r = gi.classify(issue(title="怎么安装", body="想用一下,怎么装"), [])
check("generic_usage_question", "generic_usage_question" in r["heuristic_signals"])

r = gi.classify(issue(title="合作", body="加我微信 abc123 详聊合作"), [])
check("off_topic_or_promotion", "off_topic_or_promotion" in r["heuristic_signals"])

r = gi.classify(issue(title="crash on startup",
                      body='Segmentation fault\nFile "main.py", line 42'), [])
check("real bug has no strong signal",
      "no_words_at_all" not in r["heuristic_signals"]
      and "empty_or_tiny_body" not in r["heuristic_signals"])

# ---- safety guard ---------------------------------------------------------
ok, why = gi.safety_guard(issue(title="111", body="11111111"), [], "bot")
check("guard allows empty issue", ok and not why)

ok, why = gi.safety_guard(issue(title="安装失败", body="装不上", labels=["bug"]), [], "bot")
check("guard vetoes bug label", (not ok) and any("guard_label" in w for w in why))

ok, why = gi.safety_guard(issue(title="x", body="y", assignee="alice"), [], "bot")
check("guard vetoes assigned", (not ok) and any("assigned" in w for w in why))

ok, why = gi.safety_guard(issue(title="x", body="y", milestone={"id": 3}), [], "bot")
check("guard vetoes milestone", (not ok) and "issue_has_milestone" in why)

ok, why = gi.safety_guard(issue(title="需要导出", body="希望加导出"),
                          [comment("这个在做", login="maintainer")], "bot")
check("guard vetoes external participant",
      (not ok) and any("external_participant" in w for w in why))

ok, why = gi.safety_guard(issue(title="111", body="111"),
                          [comment(gi.FIXED_REPLY, login="bot")], "bot")
check("agent's own comment is not an external participant", ok)

# ---- idempotency ----------------------------------------------------------
check("already_acknowledged true",
      gi.already_acknowledged([comment(gi.FIXED_REPLY, login="bot")], "bot"))
check("already_acknowledged false when other user",
      not gi.already_acknowledged([comment(gi.FIXED_REPLY, login="someone")], "bot"))

# ---- dedupe similarity ----------------------------------------------------
check("similarity high", gi.similarity("怎么安装依赖", "怎么安装依赖") == 1.0)
check("similarity zero", gi.similarity("abc", "xyz") == 0.0)

# ---- live-payload field shapes (regression: GitCode v5 quirk) -------------
# The real payload has `assignees: []` and no `assignee` key at all.
i = {"number": 1, "title": "x", "body": "y", "state": "open", "labels": [],
     "assignees": [{"login": "alice"}], "user": {"login": "bob"}}
ok, why = gi.safety_guard(i, [], "bot")
check("guard reads assignees[] (live shape)", (not ok) and any("assigned" in w for w in why))

i2 = dict(i, assignees=[])
ok, why = gi.safety_guard(i2, [], "bot")
check("empty assignees[] is not 'assigned'", ok)

i3 = {"number": 1, "title": "x", "body": "y", "state": "open", "labels": [],
      "assignee": "alice", "user": {"login": "bob"}}
ok, why = gi.safety_guard(i3, [], "bot")
check("guard reads bare-string assignee", (not ok) and any("assigned" in w for w in why))

i4 = {"number": 1, "title": "x", "body": "y", "state": "open", "labels": [],
      "assignee": {"login": "alice"}, "user": {"login": "bob"}}
ok, why = gi.safety_guard(i4, [], "bot")
check("guard reads dict assignee", (not ok) and any("assigned" in w for w in why))

# missing milestone key must not crash
i5 = {"number": 1, "title": "x", "body": "y", "state": "open", "labels": [],
      "user": {"login": "bob"}}
ok, why = gi.safety_guard(i5, [], "bot")
check("absent milestone key does not crash", ok)

# ---- bot handling (regression: grape_bot blocks every close) --------------
check("is_bot detects _bot suffix", gi.is_bot("grape_bot"))
check("is_bot detects -bot", gi.is_bot("ci-bot"))
check("is_bot rejects human", not gi.is_bot("andyjiao"))
check("is_bot honours explicit list", gi.is_bot("helper", ["helper"]))

# The real repo's automation account must be auto-detected with NO configuration,
# otherwise a user who omits --bot-logins would find nothing closable.
check("grape_bot auto-detected without --bot-logins", gi.is_bot("grape_bot", ()))

# A project bot replying must NOT veto the close.
bot_c = [comment("需求已分析完成", login="grape_bot")]
i6 = {"number": 1, "title": "支持一下", "body": "支持一下支持一下", "state": "open",
      "labels": [], "assignees": [], "user": {"login": "hid11339640"}}
ok, why = gi.safety_guard(i6, bot_c, "bot")
check("grape_bot alone does not veto", ok and not why)

# ...but a real human reply still must.
human_c = [comment("我这边也复现了这个问题", login="realuser")]
ok, why = gi.safety_guard(i6, human_c, "bot")
check("human reply still vetoes", (not ok) and any("external_participant" in w for w in why))

# ...and --count-bots restores the strictest behaviour.
ok, why = gi.safety_guard(i6, bot_c, "bot", ignore_bots=False)
check("count_bots treats bot as participant", (not ok) and any("external_participant" in w for w in why))

# extra bots supplied explicitly
ok, why = gi.safety_guard(i6, [comment("x", login="robot1")], "bot", bot_logins=("robot1",))
check("explicit bot list honoured", ok)

# ---- the real repo's actual worthless issues ------------------------------
# Titles/bodies taken verbatim from the live tracker.
STRONG = ("empty_or_tiny_body", "repeated_single_char", "placeholder_title",
          "no_words_at_all", "praise_only", "praise_loop", "task_farming",
          "points_farming", "maintainer_marked_junk")
real_cases = [
    (145, "支持一下", "支持一下支持一下支持一下"),
    (147, "混一下", "混一下"),
    (152, "支持一下", "支持一下"),
    (159, "很好的项目", "很好的项目"),
    (160, "很好的项目", "很好的项目"),
    (184, "挺好的项目支持支持一下", "挺好的项目支持支持一下"),
    (196, "支持一波", "支持一波"),
    (173, "好好好好好好好好好好好好好好好", "好好好好好好好好好好好好好好好"),
    (179, "支持支持", "支持支持"),
    (182, "支持下哈哈哈", "支持下哈哈哈"),
    (172, "支持", "支持"),
    (186, "支持", "支持"),
    (122, "支持开源1", "我也来支持开源支持开源"),
    (153, "支持下哈哈哈", "支持下哈哈哈支持下哈哈哈支持下哈哈哈支持下哈哈哈"),
    # reward / point farming
    (146, "拿个积分", "拿个积分拿个积分"),
    (150, "拿积分", "拿积分"),
    (162, "拿不到积分啊", "为什么呢?为什么呢?为什么呢?"),
    (168, "发了ISSUE就能拿积分了吗", "积分属实也是不好拿呀"),
    (165, "为啥积分任务完不成呢?", "为啥积分任务完不成呢???"),
    (171, "都是来拿积分的", "都是来拿积分的吧?都是来拿积分的吧?"),
]
for num, title, body in real_cases:
    r = gi.classify({"number": num, "title": title, "body": body, "labels": [],
                     "assignees": [], "user": {"login": "someone"}}, [])
    sig = r["heuristic_signals"]
    check("real junk #%s detected (%s)" % (num, title[:14]),
          any(s in sig for s in STRONG))

# ---- the dangerous class: terse but LEGITIMATE requests -------------------
# These are short, yet closing them would be a real mistake. Each must be both
# "not classified as junk" AND "vetoed by the safety guard".
legit_terse = [
    (172, "是否支持 docker 部署", "是否支持 docker 部署"),
    (175, "是否考虑 docker 部署", "是否考虑 docker 部署"),
    (168, "请问是否支持第三方其他agent", "请问是否支持第三方其他agent"),
    (133, "缺少 requirements.txt / 依赖声明", "缺少 requirements.txt / 依赖声明"),
    (178, "增加输出格式", "增加输出格式"),
    (185, "是否支持 docker 部署", "是否支持 docker 部署"),
    (190, "增加方案确认与局部重生成能力", "增加方案确认与局部重生成能力"),
    (176, "建议增加活动预算明细导出功能", "建议增加活动预算明细导出功能"),
]
for num, title, body in legit_terse:
    iss = {"number": num, "title": title, "body": body, "labels": [],
           "assignees": [], "user": {"login": "dev"}}
    r = gi.classify(iss, [])
    sig = r["heuristic_signals"]
    check("terse-but-legit #%s not junk (%s)" % (num, title[:16]),
          not any(s in sig for s in STRONG))
    ok, why = gi.safety_guard(iss, [], "bot")
    check("terse-but-legit #%s vetoed" % num, not ok)

# ---- hard distinctions verified against the live tracker ------------------
# Junk title, but the body carries a real request -> keep (this is #75).
i = {"number": 75, "title": "支持一下", "body": "能否增加支持更多的agent",
     "labels": [], "assignees": [], "user": {"login": "u"}}
ok, _ = gi.safety_guard(i, [], "bot")
check("#75 junk title + real body is KEPT", not ok)

# Junk title, but the body is a real suggestion -> keep (this is #120).
i = {"number": 120, "title": "支持开源",
     "body": "你好,在阅读和体验仓库的代码时,发现部分示例说明比较简略。建议补充核心 API 调用的详细注释。",
     "labels": [], "assignees": [], "user": {"login": "u"}}
ok, _ = gi.safety_guard(i, [], "bot")
check("#120 junk title + real suggestion is KEPT", not ok)

# Pure praise in both title and body -> worthless (#122, #153).
for num, t in [(122, ("支持开源1", "我也来支持开源支持开源")),
               (153, ("支持下哈哈哈", "支持下哈哈哈支持下哈哈哈支持下哈哈哈"))]:
    r = gi.classify({"number": num, "title": t[0], "body": t[1], "labels": [],
                     "assignees": [], "user": {"login": "u"}}, [])
    check("#%s pure praise is junk" % num,
          any(s in r["heuristic_signals"] for s in STRONG))

# Reward farming in title AND body -> worthless.
r = gi.classify({"number": 146, "title": "拿个积分", "body": "拿个积分拿个积分",
                 "labels": [], "assignees": [], "user": {"login": "u"}}, [])
check("#146 point farming is junk", "points_farming" in r["heuristic_signals"])

# A maintainer-marked junk label supports the verdict.
r = gi.classify({"number": 11, "title": "拿不动码", "body": "我是来拿积分的",
                 "labels": [{"name": "invalid"}], "assignees": [],
                 "user": {"login": "u"}}, [])
check("maintainer 'invalid' label yields supporting signal",
      "maintainer_marked_junk" in r["heuristic_signals"])

# Test placeholder posts.
r = gi.classify({"number": 1, "title": "issueTest", "body": "test", "labels": [],
                 "assignees": [], "user": {"login": "u"}}, [])
check("issueTest is junk", any(s in r["heuristic_signals"] for s in STRONG))

# A real points-feature suggestion must NOT be swept up as farming.
i = {"number": 999, "title": "建议在活动策划模块增加积分兑换说明",
     "body": "建议在活动策划模块输出里增加积分兑换功能的文档说明",
     "labels": [], "assignees": [], "user": {"login": "u"}}
ok, why = gi.safety_guard(i, [], "bot")
check("real points-feature suggestion is KEPT", not ok)

# A bare hypothetical wish is NOT a legitimate request (#34 body).
i = {"number": 34, "title": "如果支持apk就好了", "body": "如果支持apk就好了",
     "labels": [], "assignees": [], "user": {"login": "u"}}
sub = gi.legit_request_reasons(i["title"] + "\n" + i["body"])
check("#34 hypothetical wish yields no domain-substance veto",
      "domain_substance" not in sub)

# the reporter explicitly announcing task-farming
r = gi.classify({"number": 154, "title": "打扰了,就是来做任务的,不用理我",
                 "body": "完成后会自己关issue", "labels": [], "assignees": [],
                 "user": {"login": "magiccode1412"}}, [])
check("task-farming #154 detected",
      "task_farming" in r["heuristic_signals"] or "praise_only" in r["heuristic_signals"])

# real technical issues from the same repo must NOT be flagged as junk
tech_cases = [
    (143, "生成的活动预算表缺少币种与税前税后标注", "导出后无法直接使用,预算金额存在不一致,详见 analysis.md 第 3 节"),
    (144, "gen_html.py 修改活动类型、级别、日期和人数后,HTML仍保留模板旧值", "复现步骤:1. 修改 config.json 2. 运行 gen_html.py 3. 打开输出 HTML,字段未更新"),
    (133, "缺少 requirements.txt / 依赖声明", "克隆后无法确定依赖版本,建议补充依赖声明文件"),
    (115, "是否考虑 docker 部署", "希望能提供 Dockerfile 与 docker-compose 配置"),
    (111, "建议:增加键盘导航与 ARIA 标签,提升 Web UI 可访问性", "当前 Web UI 无法用键盘完整操作"),
]
for num, title, body in tech_cases:
    r = gi.classify({"number": num, "title": title, "body": body, "labels": [],
                     "assignees": [], "user": {"login": "dev"}}, [])
    sig = r["heuristic_signals"]
    check("real technical issue #%s NOT flagged" % num, not any(s in sig for s in STRONG))

# ---- ordered flow with a fake transport -----------------------------------
class FakeTransport:
    """Records an ordered call log and simulates the server."""
    def __init__(self, state="open", comments=None, fail_close=False, swallow_comment=False):
        self.state = state
        self.comments = list(comments or [])
        self.calls = []
        self.next_id = 100
        self.fail_close = fail_close
        self.swallow_comment = swallow_comment

    def __call__(self, method, path, token, params=None, json_body=None,
                 form_body=None, timeout=None):
        self.calls.append((method, path, json_body))
        if method == "GET" and path.endswith("/comments"):
            return 200, self.comments
        if method == "GET":
            return 200, {"number": 1, "title": "111", "body": "11111111",
                         "state": self.state, "labels": [], "user": {"login": "reporter"}}
        if method == "POST" and path.endswith("/comments"):
            if not self.swallow_comment:
                body = (json_body or form_body or {}).get("body")
                self.comments.append(comment(body, login="bot"))
            return 201, {"id": self.next_id}
        if method == "PATCH":
            if not self.fail_close:
                self.state = "closed"
            return 200, {"state": self.state}
        return 200, {}


orig_http = gi._http


def run_process(fake, **kw):
    gi._http = fake
    try:
        return gi._process_one("tok", "o", "r", "1", False, "bot", gi.FIXED_REPLY,
                               kw.get("force", False))
    finally:
        gi._http = orig_http


# happy path: comment must precede close
fake = FakeTransport(state="open")
res = run_process(fake)
seq = [(m, "comment" if p.endswith("/comments") else "close")
       for m, p, _ in fake.calls if m in ("POST", "PATCH")]
check("happy path ok", res["ok"] and res["action"] == "closed")
check("ORDER: reply before close", seq == [("POST", "comment"), ("PATCH", "close")])
check("final state closed", fake.state == "closed")

# comment swallowed -> must abort and NOT close
fake = FakeTransport(state="open", swallow_comment=True)
try:
    run_process(fake)
    check("swallowed comment aborts", False)
except gi.ApiError as e:
    check("swallowed comment aborts with 6", e.status == 6)
check("swallowed comment leaves issue open", fake.state == "open")
check("no PATCH attempted when reply unconfirmed",
      all(m != "PATCH" for m, _, _ in fake.calls))

# close fails -> replied but still open
fake = FakeTransport(state="open", fail_close=True)
try:
    run_process(fake)
    check("failed close raises", False)
except gi.ApiError as e:
    check("failed close raises", e.status in (1, 6))
check("issue remains open after failed close", fake.state == "open")
check("reply was still posted", any(c.get("body") == gi.FIXED_REPLY for c in fake.comments))

# guard refusal -> no writes at all
fake = FakeTransport(state="open")
gi._http = lambda m, p, t, **kw: (200, {"number": 1, "title": "bug", "body": "x",
                                        "state": "open", "labels": [{"name": "bug"}],
                                        "user": {"login": "reporter"}}) \
    if m == "GET" and not p.endswith("/comments") else (200, [])
res = gi._process_one("tok", "o", "r", "1", False, "bot", gi.FIXED_REPLY, False)
gi._http = orig_http
check("guard refusal action", res["action"] == "refused" and not res["ok"])
check("guard refusal reason recorded", bool(res["detail"].get("guard")))

# already closed -> skip
fake = FakeTransport(state="closed")
res = run_process(fake)
check("already closed skipped", res["action"] == "skip" and res["ok"])

# re-run idempotency: reply already present -> close only
fake = FakeTransport(state="open", comments=[comment(gi.FIXED_REPLY, login="bot")])
res = run_process(fake)
check("reply present -> close_only", res["action"] == "closed" and "already_present" in res["detail"])
check("no duplicate comment posted", not any(m == "POST" for m, _, _ in fake.calls))

# dry run -> no writes
fake = FakeTransport(state="open")
gi._http = fake
res = gi._process_one("tok", "o", "r", "1", True, "bot", gi.FIXED_REPLY, False)
gi._http = orig_http
check("dry run makes no writes", all(m == "GET" for m, _, _ in fake.calls))
check("dry run reports plan", "dry-run" in res["action"])

# ---- reply text -----------------------------------------------------------
check("fixed reply verbatim", gi.FIXED_REPLY == "感谢您的支持,欢迎进一步使用交流")

# ---- rate limiting (HTTP 429) --------------------------------------------
# Patch urllib.request.urlopen so the REAL _http retry loop executes.
import urllib.error  # noqa: E402
import io  # noqa: E402


class FakeResp:
    def __init__(self, status, payload):
        self.status = status
        self._buf = io.BytesIO(json.dumps(payload).encode("utf-8"))

    def read(self):
        return self._buf.read()

    def __enter__(self):
        return self

    def __exit__(self, *a):
        return False


def make_429(retry_after=None):
    hdrs = {"Retry-After": str(retry_after)} if retry_after else {}
    err = urllib.error.HTTPError(
        "https://api.gitcode.com", 429, "Too Many Requests", hdrs, None)
    err.read = lambda: b'{"error_code":429,"error_message":"429 too many requests"}'
    return err


# first N urlopen calls raise 429, then succeed
_orig_urlopen = gi.urllib.request.urlopen
_orig_sleep = gi.time.sleep
gi.time.sleep = lambda s: None


def install_urlopen(fail_times, retry_after=None):
    state = {"n": 0}

    def _open(req, timeout=None):
        state["n"] += 1
        if state["n"] <= fail_times:
            raise make_429(retry_after)
        return FakeResp(200, {"ok": True})
    gi.urllib.request.urlopen = _open
    return state


try:
    gi.RATE.__init__()
    st = install_urlopen(fail_times=2)
    status, parsed = gi._http("GET", "/ping", "tok", max_retries=3)
    check("429 then success returns 200", status == 200 and parsed == {"ok": True})
    check("429 retried the expected number of times", st["n"] == 3)

    # exhausting retries surfaces 429 instead of looping forever
    gi.RATE.__init__()
    st = install_urlopen(fail_times=99)
    try:
        gi._http("GET", "/ping", "tok", max_retries=2)
        check("429 exhaustion raises ApiError 429", False)
    except gi.ApiError as e:
        check("429 exhaustion raises ApiError 429", e.status == 429)
    check("429 exhaustion stops at max_retries", st["n"] == 3)  # 1 + 2 retries

    # a non-429 error is raised immediately (no retry)
    gi.RATE.__init__()
    st2 = {"n": 0}

    def _open404(req, timeout=None):
        st2["n"] += 1
        err = urllib.error.HTTPError("https://api.gitcode.com", 404, "Not Found", {}, None)
        err.read = lambda: b'{"message":"not found"}'
        raise err
    gi.urllib.request.urlopen = _open404
    try:
        gi._http("GET", "/missing", "tok", max_retries=3)
        check("404 is not retried", False)
    except gi.ApiError as e:
        check("404 is not retried", e.status == 404 and st2["n"] == 1)
finally:
    gi.urllib.request.urlopen = _orig_urlopen
    gi.time.sleep = _orig_sleep

# Retry-After header is honoured
rlim = gi.RateLimiter()
wait = rlim.note_429(retry_after=7.0)
check("Retry-After honoured", wait == 7.0)

# rate limiter resets after a success
rl = gi.RateLimiter()
rl.note_429()
rl.note_ok()
check("limiter resets after success", rl.consecutive_429 == 0 and rl.penalty == 0.0)

# ---- list pagination ------------------------------------------------------
# cmd_list must walk multiple pages until a short page is returned.
class PagedTransport:
    def __init__(self, total, per_page):
        self.total = total
        self.per_page = per_page
        self.seen_pages = []

    def __call__(self, method, path, token, params=None, json_body=None,
                 form_body=None, timeout=None, max_retries=None):
        import urllib.parse as _u
        page = int((params or {}).get("page", 1))
        pp = int((params or {}).get("per_page", self.per_page))
        self.seen_pages.append(page)
        start = (page - 1) * pp
        end = min(start + pp, self.total)
        return 200, [{"number": str(i), "title": "t", "state": "open",
                      "user": {"login": "u"}, "labels": []} for i in range(start, end)]


class Args:
    state = "all"; page = 1; per_page = 50; pages = 10 ** 6
    all_pages = True; json = True; no_auth = True


gi._http = PagedTransport(total=142, per_page=50)
token, owner, repo = "", "o", "r"
pages_needed = []
try:
    # replicate cmd_list's loop with recording
    collected = []
    page = 1
    while True:
        batch = gi.list_issues(token, owner, repo, state="all", page=page, per_page=50)
        pages_needed.append(page)
        if not batch or len(batch) < 50:
            collected.extend(batch)
            break
        collected.extend(batch)
        page += 1
    check("pagination collects all 142 issues", len(collected) == 142)
    check("pagination walked 3 pages", pages_needed == [1, 2, 3])
finally:
    gi._http = orig_http

# ---- agent-login identity (login vs display name) -------------------------
# whoami must report the token owner and flag a supplied login that does not match.
class WhoArgs:
    owner = "o"; repo = "r"; token = "tok"; json = True; no_auth = False
    cmd = "whoami"; agent_login = None


def run_whoami(agent_login, user_obj):
    gi._http = lambda m, p, t, **kw: (200, user_obj)
    a = WhoArgs()
    a.agent_login = agent_login
    import io as _io
    buf = _io.StringIO()
    old = sys.stdout
    sys.stdout = buf
    try:
        rc = gi.cmd_whoami(a)
    finally:
        sys.stdout = old
        gi._http = orig_http
    return rc, buf.getvalue()


USER = {"login": "yertop", "name": "yert"}

rc, out = run_whoami(None, USER)
check("whoami reports the login, not the name", '"login": "yertop"' in out)

rc, out = run_whoami("yertop", USER)
check("whoami accepts a matching agent-login", '"agent_login_matches": true' in out)
check("no warning when agent-login matches", "agent_login_warning" not in out)

# the classic mistake: passing the display name instead of the login
rc, out = run_whoami("yert", USER)
check("whoami flags display-name-instead-of-login",
      '"agent_login_matches": false' in out and "agent_login_warning" in out)

# ---- resolve_ctx warns when a write runs without an agent login ----------
class WriteArgs:
    owner = "o"; repo = "r"; token = "tok"; json = True
    cmd = "process"; agent_login = None


old_stderr = sys.stderr
warn_buf = io.StringIO()
sys.stderr = warn_buf
try:
    gi.resolve_ctx(WriteArgs())
finally:
    sys.stderr = old_stderr
check("write without agent-login warns", "WARNING" in warn_buf.getvalue())

# a read-only command must NOT warn (frictionless recon)
class ReadArgs:
    owner = "o"; repo = "r"; token = ""; json = True
    cmd = "list"; agent_login = None
    no_auth = True


old_stderr = sys.stderr
warn_buf = io.StringIO()
sys.stderr = warn_buf
try:
    gi.resolve_ctx(ReadArgs(), require_token=False)
finally:
    sys.stderr = old_stderr
check("read-only command does not warn", warn_buf.getvalue() == "")

print()
if fails:
    print("FAILURES: %d" % len(fails))
    for f in fails:
        print("  - " + f)
    sys.exit(1)
print("ALL TESTS PASSED")