"""Prototipo FastAPI para el motor propio. No es una medición de rendimiento."""
import asyncio, codecs, importlib.util, json, queue, re, threading, uuid
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import StreamingResponse, JSONResponse

MODEL='qwen2.5:3b-instruct'
DIGEST='626b4a6678b86442240e33df819e00132d3ba7dddfe1cdc4fbb18e0a9615c62d'

def import_path(name,path):
    spec=importlib.util.spec_from_file_location(name,path)
    mod=importlib.util.module_from_spec(spec);spec.loader.exec_module(mod);return mod

class Dispatcher:
    """Un único hilo posee la GPU; el event loop solo intercambia mensajes."""
    def __init__(self,engine,loop):
        self.engine=engine;self.loop=loop;self.commands=queue.Queue();self.out={};self.failure=None
        self.thread=threading.Thread(target=self.run,name='motor-propio');self.thread.start()
    def emit(self,id,item):
        out=self.out.get(id)
        if out is not None:self.loop.call_soon_threadsafe(out.put_nowait,item)
    def run(self):
        running=True
        while running:
            try:command=self.commands.get(timeout=0.001 if self.engine.jobs else None)
            except queue.Empty:command=None
            if command:
                op=command[0]
                if op=='stop':running=False;continue
                if op=='cancel':
                    try:self.engine.cancel(command[1])
                    except Exception as e:self.failure=self.failure or str(e)
                    self.out.pop(command[1],None)
                if op=='submit':
                    _,id,args,out=command;self.out[id]=out
                    try:
                        if self.failure:raise RuntimeError(self.failure)
                        self.engine.submit(id,**args)
                    except Exception as e:self.emit(id,{'error':str(e)});self.out.pop(id,None)
            if not self.engine.jobs:continue
            try:
                events=self.engine.tick()
                for id,token in events:
                    self.emit(id,{'token':token,'done':id not in self.engine.jobs})
                    if id not in self.engine.jobs:self.out.pop(id,None)
            except Exception as e:
                self.failure=str(e)
                for id in list(self.engine.jobs):
                    self.emit(id,{'error':str(e)})
                    try:self.engine.cancel(id)
                    except Exception:pass
                    self.out.pop(id,None)
        for id in list(self.engine.jobs):
            try:self.engine.cancel(id)
            except Exception:pass
    async def close(self):
        self.commands.put(('stop',));await asyncio.to_thread(self.thread.join)

def parse_calls(text):
    calls=[]
    for m in re.finditer(r'<tool_call>\s*(.*?)\s*</tool_call>',text,re.S):
        try:data=json.loads(m.group(1))
        except ValueError:return {'role':'assistant','content':text,'tool_calls':[]}
        if not isinstance(data,dict) or not isinstance(data.get('name'),str) or not isinstance(data.get('arguments'),dict):return {'role':'assistant','content':text,'tool_calls':[]}
        calls.append({'function':{'name':data['name'],'arguments':data['arguments']}})
    content=re.sub(r'<tool_call>\s*.*?\s*</tool_call>','',text,flags=re.S).strip()
    if '<tool_call>' in content or '</tool_call>' in content:return {'role':'assistant','content':text,'tool_calls':[]}
    return {'role':'assistant','content':content,'tool_calls':calls}

def create_app(engine,tokenizer,dfa=None,context=4096):
    @asynccontextmanager
    async def lifespan(app):
        app.state.dispatch=Dispatcher(engine,asyncio.get_running_loop())
        try:yield
        finally:await app.state.dispatch.close()
    app=FastAPI(lifespan=lifespan)
    @app.get('/api/tags')
    async def tags():return {'models':[{'name':MODEL,'digest':DIGEST}]}
    @app.post('/api/chat')
    @app.post('/v1/chat/completions')
    async def chat(request:Request):
        body=await request.json();openai=request.url.path.startswith('/v1/')
        if body.get('model')!=MODEL:raise HTTPException(400,'modelo desconocido')
        opts=body if openai else body.get('options',{})
        if not isinstance(opts,dict):raise HTTPException(400,'opciones inválidas')
        if not openai and set(opts)-{'temperature','seed','num_predict','num_ctx'}:raise HTTPException(400,'opción no implementada')
        if not openai and (body.get('truncate',False) or body.get('shift',False)):raise HTTPException(400,'truncado no implementado')
        if openai and body.get('response_format') not in (None,{'type':'text'}):raise HTTPException(400,'response_format no implementado')
        maximum=opts.get('max_tokens',96) if openai else opts.get('num_predict',96)
        temperature=opts.get('temperature',0.3);seed=opts.get('seed',0)
        if not isinstance(maximum,int) or maximum<1 or not isinstance(temperature,(int,float)) or temperature<0:raise HTTPException(400,'opciones inválidas')
        if not openai and opts.get('num_ctx',context)!=context:raise HTTPException(400,'contexto distinto')
        try:
            prompt=tokenizer.apply_chat_template(body['messages'],tools=body.get('tools') or None,tokenize=True,add_generation_prompt=True)
            if isinstance(prompt,dict) or hasattr(prompt,'keys'):prompt=prompt['input_ids']
        except Exception as e:raise HTTPException(400,str(e))
        if len(prompt)+maximum>context:raise HTTPException(400,'contexto excedido')
        fmt=body.get('format')
        if fmt is not None:
            allowed={'type':'object','properties':{'ok':{'type':'boolean'}},'required':['ok'],'additionalProperties':False}
            if fmt!=allowed or dfa is None:raise HTTPException(400,'solo se admite el esquema booleano de ejemplo')
        stream=body.get('stream',not openai)
        if stream and body.get('tools'):raise HTTPException(400,'herramientas en streaming no implementadas')
        id=uuid.uuid4().hex;events=asyncio.Queue()
        args=dict(prompt=prompt,max_new=maximum,temperature=temperature,seed=seed,eos=tokenizer.eos_token_id,transition=dfa if fmt else None)
        app.state.dispatch.commands.put(('submit',id,args,events))
        async def generated():
            try:
                while True:
                    item=await events.get()
                    if 'error' in item:raise RuntimeError(item['error'])
                    yield item
                    if item['done']:break
            finally:app.state.dispatch.commands.put(('cancel',id))
        if not stream:
            tokens=[];done_reason='length'
            completion_count=0
            try:
                async for event in generated():
                    completion_count+=1
                    if event['token']==tokenizer.eos_token_id:done_reason='stop'
                    else:tokens.append(event['token'])
            except RuntimeError as error:
                return JSONResponse({'error':str(error)},status_code=503)
            message=parse_calls(tokenizer.decode(tokens,skip_special_tokens=False))
            answer={'model':MODEL,'message':message,'done':True,'done_reason':done_reason,'prompt_eval_count':len(prompt),'eval_count':completion_count}
            if not openai:return answer
            calls=message.pop('tool_calls')
            if calls:message['tool_calls']=[{'id':f'call_{i}','type':'function','function':{'name':c['function']['name'],'arguments':json.dumps(c['function']['arguments'])}} for i,c in enumerate(calls)]
            return {'object':'chat.completion','model':MODEL,'choices':[{'index':0,'message':message,'finish_reason':'tool_calls' if calls else done_reason}]}
        async def stream_events():
            tokens=[];previous='';completion_count=0
            try:
                async for event in generated():
                    completion_count+=1
                    if event['token']!=tokenizer.eos_token_id:tokens.append(event['token'])
                    text=tokenizer.decode(tokens,skip_special_tokens=False)
                    # Un byte UTF-8 incompleto puede decodificarse como sustitución; se difiere.
                    if text.endswith('\ufffd') and not event['done']:continue
                    if not text.startswith(previous):raise RuntimeError('decodificación no incremental')
                    delta=text[len(previous):];previous=text
                    if openai:
                        obj={'object':'chat.completion.chunk','model':MODEL,'choices':[{'index':0,'delta':{'content':delta},'finish_reason':('stop' if event['token']==tokenizer.eos_token_id else 'length') if event['done'] else None}]}
                        yield 'data: '+json.dumps(obj,ensure_ascii=False)+'\n\n'
                    else:
                        obj={'model':MODEL,'message':{'role':'assistant','content':delta},'done':event['done']}
                        if event['done']:
                            obj.update(done_reason='stop' if event['token']==tokenizer.eos_token_id else 'length',prompt_eval_count=len(prompt),eval_count=completion_count)
                        yield json.dumps(obj,ensure_ascii=False)+'\n'
            except RuntimeError as error:
                payload=json.dumps({'error':str(error)},ensure_ascii=False)
                yield ('data: '+payload+'\n\n') if openai else (payload+'\n')
                return
            if openai:yield 'data: [DONE]\n\n'
        return StreamingResponse(stream_events(),media_type='text/event-stream' if openai else 'application/x-ndjson')
    return app
