#!/usr/bin/env python3
"""ANU operational invocation of anu_v2.owner_trigger_only capability.
Triggers ONE /gemini review on PR #162 head 8cd6e768 via OWNER_GEMINI_TRIGGER_TOKEN.
No code modification — invokes the audited capability. Token never printed."""
import json, sys, hashlib
from pathlib import Path

WS = Path("/home/jay/workspace")
sys.path.insert(0, str(WS))
HEAD = "8cd6e768ff04698606fb518096b17e7f2ea63caa"
OWNER, REPO, PR = "Jeon-Jonghyuk", "dev_workspace", 162

# token_provider: OWNER_GEMINI_TRIGGER_TOKEN from .env.keys only
def _token():
    for ln in (WS / ".env.keys").read_text().splitlines():
        if ln.startswith("OWNER_GEMINI_TRIGGER_TOKEN="):
            return ln.split("=", 1)[1].strip().strip('"').strip("'")
    raise RuntimeError("OWNER_GEMINI_TRIGGER_TOKEN missing")

captured = {}
import requests
def http_post(method, path, body, headers):
    url = "https://api.github.com" + path
    resp = requests.post(url, json=body, headers=headers, timeout=30)
    captured["status"] = resp.status_code
    # capture X-Accepted-GitHub-Permissions for 403 diagnostics
    captured["x_accepted"] = resp.headers.get("X-Accepted-GitHub-Permissions", "")
    try:
        captured["json"] = resp.json()
    except Exception:
        captured["json"] = {}
    if resp.status_code not in (200, 201):
        e = requests.HTTPError(f"HTTP {resp.status_code}")
        e.response = resp
        raise e
    return captured["json"]

from anu_v2.owner_trigger_only import OwnerTriggerOnly, trigger_for_second_review

# decision file
dec_path = WS / "memory/artifacts/task-2716-gemini-trigger-260530/owner_trigger_decision.json"
decision = {
    "schema": "anu_v2.owner_trigger_decision.v1", "task_id": "task-2716+1", "pr": PR,
    "current_head": HEAD, "queue_head": True, "current_head_confirmed": True,
    "gemini_evidence_fresh": False, "nudge_count_for_pr_head": 0,
    "allowed_action": "POST_GEMINI_REVIEW_TRIGGER_COMMENT", "comment_body": "/gemini review",
    "allowed": True,
}
dec_path.write_text(json.dumps(decision, ensure_ascii=False, indent=2))

runner = OwnerTriggerOnly(workspace_root=WS, http_post=http_post, token_provider=_token)
out = {"head_sha": HEAD, "pr": PR}
try:
    result = trigger_for_second_review(runner, pr_number=PR, head_sha=HEAD,
                                       owner=OWNER, repo=REPO, decision_path=str(dec_path))
    out["status"] = result.status
    out["http_status"] = captured.get("status")
    cj = captured.get("json", {})
    if captured.get("status") in (200, 201):
        out["comment_id"] = cj.get("id")
        out["actor"] = (cj.get("user") or {}).get("login")
        out["submittedAt"] = cj.get("created_at")
        out["html_url"] = cj.get("html_url")
except Exception as e:
    out["status"] = "FAILED"
    out["http_status"] = captured.get("status")
    out["x_accepted_github_permissions"] = captured.get("x_accepted", "")
    out["error"] = str(e)[:200]
    cj = captured.get("json", {})
    out["github_message"] = cj.get("message", "")
print(json.dumps(out, ensure_ascii=False))
