#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Exchange XiaoE platform credentials for an E10 eteamId.

This compatibility helper is executed only by weaver-work-cli. It uses the
Python standard library, writes one JSON result to stdout, keeps TLS certificate
verification enabled, and refuses redirects that could leak Authorization to a
different origin.
"""

import json
import os
import ssl
import sys
import urllib.error
import urllib.request
from urllib.parse import urljoin, urlsplit


MAX_REDIRECTS = 5
ETEAM_ID_PATH = "/spec-apps/api/app/rpachat/skill/extend/eteamId"


def _effective_port(parts):
    if parts.port is not None:
        return parts.port
    return 443 if parts.scheme == "https" else 80


def _same_origin(left, right):
    return (
        left.scheme == right.scheme
        and left.hostname == right.hostname
        and _effective_port(left) == _effective_port(right)
    )


class _SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        current = urlsplit(req.full_url)
        target_url = urljoin(req.full_url, newurl)
        target = urlsplit(target_url)
        safe_upgrade = (
            current.scheme == "http"
            and target.scheme == "https"
            and current.hostname == target.hostname
        )
        if target.scheme not in ("http", "https") or target.username or target.password:
            raise urllib.error.HTTPError(target_url, 403, "unsafe XiaoE redirect", headers, fp)
        if not _same_origin(current, target) and not safe_upgrade:
            raise urllib.error.HTTPError(target_url, 403, "cross-origin XiaoE redirect", headers, fp)

        redirects = getattr(req, "_xiaoe_redirects", 0) + 1
        if redirects > MAX_REDIRECTS:
            raise urllib.error.HTTPError(target_url, 310, "too many XiaoE redirects", headers, fp)

        redirected = urllib.request.Request(
            target_url,
            data=req.data,
            headers=dict(req.header_items()),
            method=req.get_method(),
        )
        redirected._xiaoe_redirects = redirects
        return redirected


def _post_json(url, token, domain):
    body = json.dumps({"domain": domain}).encode("utf-8")
    request = urllib.request.Request(
        url,
        data=body,
        headers={
            "authorization": token,
            "Content-Type": "application/json",
        },
        method="POST",
    )
    opener = urllib.request.build_opener(
        _SafeRedirectHandler(),
        urllib.request.HTTPSHandler(context=ssl.create_default_context()),
    )
    try:
        with opener.open(request, timeout=15) as response:
            raw = response.read().decode("utf-8")
    except urllib.error.HTTPError as error:
        detail = error.read().decode("utf-8", "ignore")[:200]
        raise RuntimeError(f"HTTP {error.code}: {detail}") from error
    return json.loads(raw)


def main():
    domain = sys.argv[1].strip() if len(sys.argv) > 1 else "https://www.e-cology.com.cn"
    token = os.getenv("XIAOE_USER_TOKEN", "").strip()
    erpa = os.getenv("XIAOE_DOMAIN", "").strip()
    if not token or not erpa:
        raise RuntimeError("missing XIAOE_USER_TOKEN or XIAOE_DOMAIN")

    endpoint = f"{erpa.rstrip('/')}{ETEAM_ID_PATH}"
    data = _post_json(endpoint, token, domain)
    business_code = data.get("code")
    business_data = data.get("data") or {}
    eteam_id = business_data.get("eteamId") if isinstance(business_data, dict) else None
    if business_code not in ("0000", 200) or not eteam_id:
        raise RuntimeError(f"XiaoE exchange failed with business code {business_code}")

    print(json.dumps({
        "eteamId": eteam_id,
        "code": business_code,
        "msg": data.get("msg"),
    }, ensure_ascii=False))


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(json.dumps({"code": "ERROR", "msg": str(error)}, ensure_ascii=False), file=sys.stderr)
        sys.exit(1)
