"""Task-scoped Yunxiao OpenAPI transport; never serialize credentials."""
import json,shlex,urllib.request,urllib.error
from pathlib import Path
ROOT=Path(__file__).resolve().parents[3]
ENV={}
for line in (ROOT/'config/local/yunxiao.env').read_text().splitlines():
    if not line.strip() or line.lstrip().startswith('#') or '=' not in line: continue
    key,val=line.removeprefix('export ').split('=',1)
    vals=shlex.split(val,comments=True); ENV[key.strip()]=vals[0] if vals else ''
assert ENV.get('YUNXIAO_TOKEN') and ENV.get('YUNXIAO_CREATOR_NAME')=='兰海军'
ORG=ENV['YUNXIAO_ORGANIZATION_ID'];SPACE=ENV['YUNXIAO_PROJECT_ID']
PREFIX=f'/oapi/v1/projex/organizations/{ORG}'

def api(method,path,body=None):
    request=urllib.request.Request('https://openapi-rdc.aliyuncs.com'+path,
        data=None if body is None else json.dumps(body,ensure_ascii=False).encode(),method=method,
        headers={'x-yunxiao-token':ENV['YUNXIAO_TOKEN'],'Content-Type':'application/json'})
    try:
        with urllib.request.urlopen(request,timeout=45) as r:
            raw=r.read();return json.loads(raw) if raw else None
    except urllib.error.HTTPError as e:
        raw=e.read().decode(errors='replace')
        try:
            d=json.loads(raw);detail={k:d.get(k) for k in ['errorCode','errorMessage','code','message'] if k in d}
        except Exception: detail='non-JSON error'
        raise RuntimeError(f'{method} {path}: HTTP {e.code}: {detail}') from None

def compact(item):
    return {k:item.get(k) for k in ['id','serialNumber','subject','assignedTo','status','parentId','workitemType']}
