#!/usr/bin/env python3
"""WarmPix image-to-3D API client. Requires Python 3.10+ and requests.

pip install requests
python img3d_client.py image.png -o model.glb
python img3d_client.py image.png -o model.glb --preserve-reference
python img3d_client.py --job-id SAVED_JOB_ID -o model.glb

Keep the private cookie file to poll/download/retry the same jobs later. It is
not interchangeable with a browser's session. TLS verification stays enabled.
"""
from __future__ import annotations
import argparse, hashlib, http.cookiejar, json, mimetypes, os, struct, sys, tempfile, time, uuid
from pathlib import Path
from urllib.parse import urlparse
import requests

BASE_URL='https://img3d.warmpix.com'
TRANSIENT={429,502,503,504}

class ApiError(RuntimeError): pass

def validate_glb(path:Path,expected_bytes:int):
    """Check the GLB container before publishing a download, without reading BIN data into RAM."""
    size=path.stat().st_size
    if size!=expected_bytes: raise ApiError('Downloaded size differs from recorded model size.')
    with path.open('rb') as handle:
        header=handle.read(12)
        if len(header)!=12: raise ApiError('Incomplete GLB header')
        magic,version,length=struct.unpack('<4sII',header)
        if magic!=b'glTF' or version!=2 or length!=size or size<20:
            raise ApiError('Invalid or truncated GLB download')
        document=None;binary_length=None;index=0
        while handle.tell()<size:
            chunk_header=handle.read(8)
            if len(chunk_header)!=8: raise ApiError('Incomplete GLB chunk header')
            chunk_length,chunk_type=struct.unpack('<II',chunk_header)
            if chunk_length%4 or handle.tell()+chunk_length>size:
                raise ApiError('Invalid GLB chunk length')
            if index==0 and chunk_type!=0x4e4f534a:
                raise ApiError('GLB JSON chunk must come first')
            if chunk_type==0x4e4f534a:
                if index!=0: raise ApiError('Duplicate GLB JSON chunk')
                try: document=json.loads(handle.read(chunk_length).decode('utf-8'))
                except (UnicodeError,ValueError) as exc:
                    raise ApiError('Invalid GLB JSON content') from exc
            else:
                if chunk_type==0x004e4942:
                    if index!=1: raise ApiError('GLB binary chunk must come second')
                    binary_length=chunk_length
                # Unknown extension chunks are allowed by the GLB specification.
                handle.seek(chunk_length,os.SEEK_CUR)
            index+=1
    if not isinstance(document,dict) or not isinstance(document.get('asset'),dict) or document['asset'].get('version')!='2.0':
        raise ApiError('Unsupported or missing glTF asset version')
    buffers=document.get('buffers',[])
    if not isinstance(buffers,list) or any(not isinstance(buffer,dict) for buffer in buffers):
        raise ApiError('Invalid GLB buffer descriptions')
    if buffers and 'uri' not in buffers[0]:
        declared=buffers[0].get('byteLength')
        if type(declared) is not int or declared<1 or binary_length is None or not 0<=binary_length-declared<=3:
            raise ApiError('GLB binary buffer length does not match its JSON description')


class Client:
    def __init__(self, base_url: str=BASE_URL, cookie_file: Path|str=Path('.warmpix-img3d.cookies')):
        url=urlparse(base_url)
        if url.scheme!='https' or not url.netloc or url.username or url.password or url.query or url.fragment:
            raise ValueError('Use an HTTPS base URL without credentials, query or fragment.')
        self.base=base_url.rstrip('/')
        self.cookie_file=Path(cookie_file).expanduser()
        self.session=requests.Session()
        self.session.headers['User-Agent']='WarmPix-Img3D-Client/2.1'
        jar=http.cookiejar.MozillaCookieJar()
        if self.cookie_file.exists(): jar.load(str(self.cookie_file),ignore_discard=True,ignore_expires=False)
        self.session.cookies=jar
        self.csrf=''

    def close(self): self.session.close()

    def save_cookies(self):
        self.cookie_file.parent.mkdir(parents=True,exist_ok=True)
        fd,temp=tempfile.mkstemp(prefix='.wp3d-cookie-',dir=self.cookie_file.parent)
        os.close(fd)
        try:
            self.session.cookies.save(temp,ignore_discard=True,ignore_expires=False)
            os.chmod(temp,0o600)
            os.replace(temp,self.cookie_file)
        finally:
            if os.path.exists(temp): os.unlink(temp)

    @staticmethod
    def check(response):
        if response.ok: return
        try:
            payload=response.json()
            detail=payload.get('detail','request_failed') if isinstance(payload,dict) else 'upstream_http_error'
        except ValueError: detail='upstream_http_error'
        if not isinstance(detail,str): detail=json.dumps(detail,ensure_ascii=False)
        raise ApiError(f'HTTP {response.status_code}: {detail}')

    def get(self,path:str):
        for attempt in range(4):
            try:
                response=self.session.get(self.base+path,timeout=(20,90))
                if response.status_code in TRANSIENT and attempt<3:
                    response.close();time.sleep(min(2**attempt,8));continue
                self.check(response)
                return response.json()
            except (requests.ConnectionError,requests.Timeout):
                if attempt==3: raise
                time.sleep(min(2**attempt,8))
        raise ApiError('GET retries exhausted')

    def connect(self):
        data=self.get('/api/session')
        self.csrf=data['csrf']
        self.save_cookies()
        return self

    def wait_ready(self,timeout:float=600):
        deadline=time.monotonic()+timeout
        while time.monotonic()<deadline:
            health=self.get('/api/health')
            if health.get('ready'): return health
            print(f"Engine: {health.get('status','starting')}; queue={health.get('queue',0)}",flush=True)
            time.sleep(3)
        raise TimeoutError('Worker not ready before the deadline. No job was submitted.')

    def submit(self,image:Path|str, *, seed:int=42,resolution:int=1024,texture:int=4096,
               quality:str='detail',preserve_reference:bool=False,idempotency_key:str|None=None):
        image=Path(image)
        if not self.csrf: raise ApiError('Call connect() before submitting.')
        if not image.is_file() or image.stat().st_size>20*1024**2: raise ValueError('Image missing or exceeds 20 MiB.')
        if resolution not in (1024,1536) or texture not in (1024,2048,4096) or quality not in ('standard','detail') or not 0<=seed<=2147483647:
            raise ValueError('Invalid generation settings.')
        key=idempotency_key or str(uuid.uuid4())
        print(f'Idempotency-Key: {key}',flush=True)
        fields={'seed':str(seed),'resolution':str(resolution),'texture':str(texture),
                'texture_quality':quality,'preserve_reference':str(preserve_reference).lower()}
        for attempt in range(4):
            try:
                # Reopen on every retry: a consumed file stream must never be reused.
                with image.open('rb') as handle:
                    response=self.session.post(self.base+'/api/jobs',
                        headers={'X-CSRF-Token':self.csrf,'Idempotency-Key':key},data=fields,
                        files={'image':(image.name,handle,mimetypes.guess_type(image.name)[0] or 'application/octet-stream')},
                        timeout=(20,300))
                if response.status_code in TRANSIENT and attempt<3:
                    response.close();time.sleep(min(2**attempt,8));continue
                self.check(response)
                job=response.json()
                print(f"Job: {job['id']} ({job['state']})",flush=True)
                return job
            except (requests.ConnectionError,requests.Timeout):
                if attempt==3:
                    raise ApiError(f'Submission outcome is uncertain. Keep the cookie file and retry the SAME image/settings with --idempotency-key {key}.')
                time.sleep(min(2**attempt,8))
        raise ApiError('Submission retries exhausted')

    def wait(self,job_id:str, *, timeout:float=1800,poll_interval:float=3):
        deadline=time.monotonic()+timeout;last=None
        while time.monotonic()<deadline:
            job=self.get(f'/api/jobs/{job_id}')
            signature=(job['state'],job['stage'],job.get('ahead'))
            if signature!=last:
                print(f"{job_id}: {job['state']} / {job['stage']}"+(f"; ahead={job['ahead']}" if 'ahead' in job else ''),flush=True)
                last=signature
            if job['state']=='complete': return job
            if job['state']=='failed': raise ApiError(f"Job {job_id} failed: {job.get('error')}. Inspect the job and explicitly retry it when appropriate.")
            time.sleep(max(1,poll_interval))
        raise TimeoutError(f'Polling deadline reached. The server job is NOT cancelled. Resume with --job-id {job_id} and the same cookie file.')

    def retry(self,job_id:str):
        response=self.session.post(self.base+f'/api/jobs/{job_id}/retry',headers={'X-CSRF-Token':self.csrf},timeout=(20,90))
        self.check(response)
        return response.json()

    def download(self,job_id:str,output:Path|str, *, overwrite:bool=False,expected_bytes:int|None=None):
        output=Path(output);output.parent.mkdir(parents=True,exist_ok=True)
        if output.exists() and not overwrite: raise FileExistsError(f'{output} exists; use --overwrite deliberately.')
        if expected_bytes is None:
            job=self.get(f'/api/jobs/{job_id}')
            if not isinstance(job,dict) or job.get('state')!='complete':
                raise ApiError('The job is not complete; no model was downloaded.')
            expected_bytes=job.get('bytes')
        if type(expected_bytes) is not int or not 20<=expected_bytes<=0xffffffff:
            raise ApiError('The completed job has an invalid recorded model size.')
        fd,temp=tempfile.mkstemp(prefix=output.name+'.',suffix='.part',dir=output.parent)
        os.close(fd)
        try:
            digest=hashlib.sha256();received=0
            with self.session.get(self.base+f'/api/jobs/{job_id}/model',stream=True,timeout=(20,300)) as response:
                self.check(response)
                content_length=response.headers.get('Content-Length')
                if content_length is not None and response.headers.get('Content-Encoding','identity').lower() in ('','identity'):
                    try: declared_length=int(content_length)
                    except ValueError as exc: raise ApiError('Invalid download Content-Length') from exc
                    if declared_length!=expected_bytes:
                        raise ApiError('Download Content-Length differs from recorded model size.')
                with open(temp,'wb') as handle:
                    for chunk in response.iter_content(1024*1024):
                        if not chunk: continue
                        received+=len(chunk)
                        if received>expected_bytes: raise ApiError('Download exceeds the recorded model size.')
                        handle.write(chunk);digest.update(chunk)
            validate_glb(Path(temp),expected_bytes)
            if overwrite: os.replace(temp,output)
            else:
                # Atomic no-clobber publish; do not overwrite a concurrently created output.
                os.link(temp,output);os.unlink(temp)
            return {'path':str(output.resolve()),'bytes':received,'sha256':digest.hexdigest()}
        finally:
            if os.path.exists(temp): os.unlink(temp)


def main():
    parser=argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('image',nargs='?',type=Path)
    parser.add_argument('-o','--output',type=Path,default=Path('model.glb'))
    parser.add_argument('--base-url',default=BASE_URL)
    parser.add_argument('--session-file',type=Path,default=Path('.warmpix-img3d.cookies'))
    parser.add_argument('--resolution',type=int,choices=(1024,1536),default=1024)
    parser.add_argument('--texture',type=int,choices=(1024,2048,4096),default=4096)
    parser.add_argument('--quality',choices=('standard','detail'),default='detail')
    parser.add_argument('--seed',type=int,default=42)
    parser.add_argument('--preserve-reference',action='store_true')
    parser.add_argument('--idempotency-key')
    parser.add_argument('--job-id',help='Resume a known job instead of submitting a new one.')
    parser.add_argument('--retry-failed',action='store_true',help='Explicitly retry --job-id if failed.')
    parser.add_argument('--timeout',type=float,default=1800,help='Polling deadline in seconds, including queue time.')
    parser.add_argument('--record',type=Path,help='Write non-secret result/metadata JSON for audit.')
    parser.add_argument('--overwrite',action='store_true')
    args=parser.parse_args()
    if not args.job_id and not args.image: parser.error('Provide an image or --job-id.')
    if args.image and args.job_id: parser.error('Choose an image OR --job-id, not both.')
    if args.retry_failed and not args.job_id: parser.error('--retry-failed requires --job-id.')
    if args.timeout<=0: parser.error('--timeout must be positive.')
    if args.output.exists() and not args.overwrite: parser.error('Output exists; choose another path or use --overwrite.')
    client=Client(args.base_url,args.session_file)
    begin=time.monotonic()
    try:
        client.connect()
        if args.job_id:
            job=client.get(f'/api/jobs/{args.job_id}')
            if args.retry_failed and job['state']=='failed':
                client.wait_ready();job=client.retry(args.job_id)
        else:
            client.wait_ready()
            job=client.submit(args.image,seed=args.seed,resolution=args.resolution,texture=args.texture,
                quality=args.quality,preserve_reference=args.preserve_reference,idempotency_key=args.idempotency_key)
        job=client.wait(job['id'],timeout=args.timeout)
        result=client.download(job['id'],args.output,overwrite=args.overwrite,expected_bytes=job.get('bytes'))
        metadata=None;metadata_error=None
        try:
            metadata=client.get(f"/api/jobs/{job['id']}/metadata")
            if not isinstance(metadata,dict): raise ApiError('Export metadata is not a JSON object.')
        except (ApiError,requests.RequestException,ValueError) as exc:
            metadata=None;metadata_error=str(exc)
            print(f'Warning: the model was saved, but export metadata is unavailable: {metadata_error}',file=sys.stderr)
        record={'job':job,'download':result,'export':metadata,'client_elapsed_seconds':round(time.monotonic()-begin,3)}
        if metadata_error is not None: record['metadata_error']=metadata_error
        if args.record:
            args.record.parent.mkdir(parents=True,exist_ok=True)
            args.record.write_text(json.dumps(record,indent=2,ensure_ascii=False)+'\n')
        print(f"Saved {result['path']} ({result['bytes']:,} bytes)\nSHA-256: {result['sha256']}")
        print(f"Server processing: {job.get('duration',0):.2f}s; total client time: {record['client_elapsed_seconds']:.2f}s")
        return 0
    except (ApiError,requests.RequestException,ValueError,OSError,TimeoutError) as exc:
        print(str(exc),file=sys.stderr);return 1
    finally: client.close()

if __name__=='__main__':raise SystemExit(main())
