"""Vertex vectors. No keys on disk, access token stays inside the HTTP header."""
import base64,json,subprocess,time,threading,urllib.request,urllib.error
import numpy as np
PROJECT='forge-dev-492809'; REGION='us-central1'
MM='gemini-embedding-2-preview'; TEXT='gemini-embedding-001'
VECTOR_SET='gemini-embedding-2-preview'
_lock=threading.Lock();_token='';_expires=0

def predict(model,instances,parameters=None):
    global _token,_expires
    with _lock:
        if time.time()>_expires:
            _token=subprocess.check_output(['gcloud','auth','print-access-token'],stderr=subprocess.DEVNULL,text=True).strip();_expires=time.time()+2400
    body={'instances':instances}
    if parameters:body['parameters']=parameters
    url=f'https://{REGION}-aiplatform.googleapis.com/v1/projects/{PROJECT}/locations/{REGION}/publishers/google/models/{model}:predict'
    for attempt in range(2):
        try:
            req=urllib.request.Request(url,json.dumps(body).encode(),{'Authorization':'Bearer '+_token,'Content-Type':'application/json'})
            with urllib.request.urlopen(req,timeout=120) as r:return json.load(r)['predictions']
        except urllib.error.HTTPError as e:
            if e.code not in (429,500,503) or attempt:raise RuntimeError(f'Vertex {model}: HTTP {e.code}') from None
            time.sleep(4)

def unit(v):
    a=np.asarray(v,dtype=np.float32);return a/max(float(np.linalg.norm(a)),1e-12)

def multimodal(text=None,image=None):
    global _token,_expires
    parts=[]
    if text:parts.append({'text':text})
    if image:
        import mimetypes
        parts.append({'inlineData':{'mimeType':mimetypes.guess_type(str(image))[0] or 'image/jpeg','data':base64.b64encode(open(image,'rb').read()).decode()}})
    with _lock:
        if time.time()>_expires:
            _token=subprocess.check_output(['gcloud','auth','print-access-token'],stderr=subprocess.DEVNULL,text=True).strip();_expires=time.time()+2400
    body={'content':{'parts':parts},'outputDimensionality':768}
    url=f'https://{REGION}-aiplatform.googleapis.com/v1/projects/{PROJECT}/locations/{REGION}/publishers/google/models/{MM}:embedContent'
    for attempt in range(2):
        try:
            req=urllib.request.Request(url,json.dumps(body).encode(),{'Authorization':'Bearer '+_token,'Content-Type':'application/json'})
            with urllib.request.urlopen(req,timeout=120) as r:v=unit(json.load(r)['embedding']['values'])
            result={}
            if image:result['imageEmbedding']=v
            if text:result['textEmbedding']=v
            return result
        except urllib.error.HTTPError as exc:
            if exc.code not in (429,500,503) or attempt:raise RuntimeError(f'Vertex {MM}: HTTP {exc.code}') from None
            time.sleep(4)


def text_vector(text,query=False):
    return unit(predict(TEXT,[{'content':text,'task_type':'RETRIEVAL_QUERY' if query else 'RETRIEVAL_DOCUMENT'}],{'outputDimensionality':768})[0]['embeddings']['values'])
