"""Claude Code governor hook. No transcript, file content or tool output is uploaded."""
import hashlib,json,os,sys,time,uuid
from pathlib import Path
from urllib.parse import urlparse
import urllib.request
class FixedHost(urllib.request.HTTPRedirectHandler):
    def redirect_request(self,*args):return None
def api(path,body=None):
    base=os.environ['MULTIPRA_PORTAL'].rstrip('/')
    if urlparse(base).scheme!='https':raise ValueError('HTTPS required')
    key=Path(os.environ['MULTIPRA_KEY_FILE']).read_text().strip()
    req=urllib.request.Request(base+'/api/v1/engagement/governor/events'+path,data=json.dumps(body).encode() if body else None,headers={'Authorization':'Bearer '+key,'Content-Type':'application/json'})
    with urllib.request.build_opener(FixedHost).open(req,timeout=5) as r:return json.load(r)
def run(h):
    event=h['hook_event_name'];tool=h.get('tool_name','');inp=h.get('tool_input') or {}
    root=Path(os.environ['MULTIPRA_PROJECT_ROOT']).resolve(strict=True)
    cwd=Path(h.get('cwd') or root).resolve()
    path=inp.get('file_path') or inp.get('notebook_path') or ''
    resolved=(cwd/path).resolve() if path else None
    data=dict(event=event,request_id=str(uuid.uuid4()),session_id=h['session_id'],tool=tool,command=inp.get('command','') if event=='PreToolUse' else '',path=str(resolved or ''),outside=bool(resolved and not resolved.is_relative_to(root)),action_hash=hashlib.sha256(json.dumps([event,h['session_id'],h.get('tool_use_id'),tool,inp,str(cwd)],sort_keys=True,separators=(',',':')).encode()).hexdigest())
    answer=api('',data)
    if event!='PreToolUse':return {}
    until=time.monotonic()+145
    while answer['decision']=='Pending' and time.monotonic()<until:
        time.sleep(2);answer=api('/'+answer['id'])
    decision=answer['decision'];reason=answer.get('reason','Unknown policy result')
    if decision not in ('Allow','Advise'):return deny(reason if decision=='Block' else 'Portal approval timed out.')
    if decision=='Advise':return {'systemMessage':reason,'hookSpecificOutput':{'hookEventName':'PreToolUse','additionalContext':reason}}
    return {'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow','permissionDecisionReason':reason}}
def deny(reason):
    return {'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'deny','permissionDecisionReason':reason}}
if __name__=='__main__':
    try:out=run(json.load(sys.stdin))
    except Exception:out=deny('Governor unavailable or invalid input. Action blocked.')
    print(json.dumps(out))

