"""Task-scoped OpenAPI transport; credentials remain in ignored local config."""
import json
import pathlib
import urllib.request
import urllib.error

ROOT = pathlib.Path(__file__).resolve().parents[3]
ORG = '60069db88deaa14d9e02b875'
SPACE = 'dd2f708d1702891ff45b6f5d99'
PREFIX = f'/oapi/v1/projex/organizations/{ORG}'

def api(method, path, body=None):
    env = {}
    for line in (ROOT / 'config/local/yunxiao.env').read_text().splitlines():
        if '=' in line and not line.lstrip().startswith('#'):
            key, value = line.removeprefix('export ').split('=', 1)
            env[key.strip()] = value.strip().strip('\"\'')
    assert env.get('YUNXIAO_TOKEN') and env.get('YUNXIAO_CREATOR_NAME') == '姜阳'
    req = 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(req, timeout=45) as response:
            raw = response.read()
            return json.loads(raw) if raw else None
    except urllib.error.HTTPError as exc:
        raise RuntimeError(f'{method} {path}: HTTP {exc.code}: {exc.read().decode()[:800]}') from None

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