"""CMP 0.17.0 第三方会话接入示例。直接运行只登录、读取身份并注销。"""
import http.cookiejar
import json
import os
import urllib.parse
import urllib.request


class Client:
    def __init__(self):
        self.origin = os.environ['CMP_ORIGIN'].rstrip('/')
        parsed = urllib.parse.urlsplit(self.origin)
        if parsed.scheme != 'https' and not (parsed.scheme == 'http' and parsed.hostname in ('localhost', '127.0.0.1', '::1')):
            raise ValueError('正式入口使用 HTTPS；HTTP 仅用于本机回环测试')
        if parsed.path or parsed.query or parsed.fragment or parsed.username:
            raise ValueError('CMP_ORIGIN 只填写协议、主机和端口，不包含路径或凭据')
        self.username = os.environ['CMP_USERNAME']
        self.password = os.environ['CMP_PASSWORD']
        self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))

    def call(self, method, path, body=None, *, idempotency_key=None):
        headers = {'Origin': self.origin, 'Accept': 'application/json'}
        if method not in ('GET', 'HEAD', 'OPTIONS'):
            token = self.call('GET', '/api/auth/v1/csrf')['data']['csrf_token']
            headers['X-CSRF-Token'] = token
        if idempotency_key:
            headers['Idempotency-Key'] = idempotency_key
        payload = None
        if body is not None:
            headers['Content-Type'] = 'application/json'
            payload = json.dumps(body).encode()
        request = urllib.request.Request(self.origin + path, data=payload, headers=headers, method=method)
        with self.opener.open(request, timeout=30) as response:
            content = response.read()
            return json.loads(content) if content else None


if __name__ == '__main__':
    client = Client()
    client.call('POST', '/api/auth/v1/login', {'username': client.username, 'password': client.password})
    me = client.call('GET', '/api/auth/v1/me')['data']
    print(json.dumps({'id': me['id'], 'active_tenant_id': me.get('active_tenant_id')}, ensure_ascii=False))
    client.call('POST', '/api/auth/v1/logout', {})
