# -*- coding: utf-8 -*-
"""Task-scoped Yunxiao OpenAPI transport; credentials stay in local config."""
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)
    values = shlex.split(val, comments=True)
    ENV[key.strip()] = values[0] if values else ''

assert ENV.get('YUNXIAO_TOKEN')
assert 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 response:
            raw = response.read()
            return json.loads(raw) if raw else None
    except urllib.error.HTTPError as error:
        raw = error.read().decode(errors='replace')
        try:
            data = json.loads(raw)
            detail = {key: data.get(key) for key in ['errorCode', 'errorMessage', 'code', 'message'] if key in data}
        except Exception:
            detail = 'non-JSON error'
        raise RuntimeError(f'{method} {path}: HTTP {error.code}: {detail}') from None

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