#!/usr/bin/env python3
# Local stand-in for the Messages API so real Claude Code runs without spending anything.
import json,time,sys
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
LOG=sys.argv[2]
def log(s):
    open(LOG,'a').write(f"{time.time():.3f} MOCK {s}\n")
class H(BaseHTTPRequestHandler):
    protocol_version='HTTP/1.1'
    def log_message(self,*a):pass
    def do_GET(self):
        b=b'{}';self.send_response(200);self.send_header('content-type','application/json');self.send_header('content-length',str(len(b)));self.end_headers();self.wfile.write(b)
    def do_POST(self):
        n=int(self.headers.get('content-length',0));body=json.loads(self.rfile.read(n) or b'{}')
        if 'count_tokens' in self.path:
            b=b'{"input_tokens":10}';self.send_response(200);self.send_header('content-type','application/json');self.send_header('content-length',str(len(b)));self.end_headers();self.wfile.write(b);return
        msgs=body.get('messages',[]);tools=[t.get('name') for t in body.get('tools',[]) or []]
        last=msgs[-1] if msgs else {}
        c=last.get('content');txt=c if isinstance(c,str) else ' '.join(x.get('text','') for x in c if isinstance(x,dict) and x.get('type')=='text')
        hasres='tool_result' in json.dumps(msgs)
        block={'type':'text','text':'done'};stop='end_turn'
        low=json.dumps(msgs).lower()
        if tools and not hasres:
            if 'scenariobash' in low:
                block={'type':'tool_use','id':'toolu_01A','name':'Bash','input':{'command':'touch made-by-test.txt','description':'make a file'}};stop='tool_use'
            elif 'scenarioask' in low:
                block={'type':'tool_use','id':'toolu_01B','name':'AskUserQuestion','input':{'questions':[{'question':'Which colour?','header':'Colour','multiSelect':False,'options':[{'label':'Red','description':'r'},{'label':'Blue','description':'b'}]}]}};stop='tool_use'
        self.send_response(200);self.send_header('content-type','text/event-stream');self.send_header('cache-control','no-cache');self.send_header('connection','close');self.end_headers()
        def ev(t,d):
            self.wfile.write(f"event: {t}\ndata: {json.dumps(d)}\n\n".encode());self.wfile.flush()
        ev('message_start',{'type':'message_start','message':{'id':'msg_1','type':'message','role':'assistant','model':body.get('model','m'),'content':[],'stop_reason':None,'stop_sequence':None,'usage':{'input_tokens':1,'output_tokens':1}}})
        if block['type']=='text':
            ev('content_block_start',{'type':'content_block_start','index':0,'content_block':{'type':'text','text':''}})
            ev('content_block_delta',{'type':'content_block_delta','index':0,'delta':{'type':'text_delta','text':block['text']}})
        else:
            ev('content_block_start',{'type':'content_block_start','index':0,'content_block':{'type':'tool_use','id':block['id'],'name':block['name'],'input':{}}})
            ev('content_block_delta',{'type':'content_block_delta','index':0,'delta':{'type':'input_json_delta','partial_json':json.dumps(block['input'])}})
        ev('content_block_stop',{'type':'content_block_stop','index':0})
        ev('message_delta',{'type':'message_delta','delta':{'stop_reason':stop,'stop_sequence':None},'usage':{'output_tokens':1}})
        ev('message_stop',{'type':'message_stop'})
        if tools: log(f"sent {block.get('name','text')} stop={stop}")
        self.close_connection=True
ThreadingHTTPServer(('127.0.0.1',int(sys.argv[1])),H).serve_forever()
