#!/usr/bin/env python3
"""经纬表应用接入。使用 Python 3 标准库和管理员发来的完整 HTTPS 分享链接。"""
import argparse
import getpass
import hashlib
import json
import os
from pathlib import Path
import re
import secrets
import sys
import tempfile
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qs, quote, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener


class IntegrationError(Exception):
    """Show actionable diagnostics without printing links, tokens or response bodies."""


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def parse_link(link):
    url = urlsplit(link.strip())
    fields = parse_qs(url.fragment, strict_parsing=True)
    tokens = fields.get("share", [])
    if (url.scheme != "https" or not url.hostname or url.username or url.password
            or url.path.rstrip("/") != "/developers" or url.query
            or len(tokens) != 1 or not re.fullmatch(r"[a-zA-Z0-9._~-]{20,256}", tokens[0])):
        raise IntegrationError("请输入管理员分享的完整 HTTPS 链接，包括 #share= 后的部分。")
    return "https://" + url.netloc, tokens[0]


def request(opener, origin, path, token, payload=None):
    encoded = None if payload is None else json.dumps(payload).encode()
    req = Request(origin + path, data=encoded, headers={
        "Authorization": "Bearer " + token, "Content-Type": "application/json",
        "Accept": "application/json", "User-Agent": "Jingwei-Connect/1"})
    try:
        with opener.open(req, timeout=30) as response:
            return json.load(response)
    except HTTPError as error:
        try:
            code = json.load(error).get("error", {}).get("code", "")
        except (ValueError, AttributeError):
            code = ""
        hints = {401: "请检查链接有效期或应用密钥。", 403: "请检查应用当前的空间授权。",
                 404: "请检查链接是否有效。", 409: "如果已在浏览器领取，请使用先前保存的密钥。",
                 410: "该链接已失效，请向管理员获取新链接。", 429: "请稍后重试。"}
        raise IntegrationError(f"{path} 返回 HTTP {error.code} {code}。{hints.get(error.code, '')}") from None


def private_write(path, data, create_only=False):
    # Publish a complete mode-0600 file; two clients racing to claim reuse one proof.
    fd, name = tempfile.mkstemp(dir=path.parent)
    try:
        with os.fdopen(fd, "wb") as handle:
            handle.write(data)
            handle.flush()
            os.fsync(handle.fileno())
        if create_only:
            try:
                os.link(name, path)
            except FileExistsError:
                pass
        else:
            os.replace(name, path)
    finally:
        if os.path.exists(name):
            os.unlink(name)


def write_json(path, body):
    private_write(path, (json.dumps(body, indent=2, ensure_ascii=False) + "\n").encode())


def connect(link, base_dir, docs_only=False):
    origin, share = parse_link(link)
    opener = build_opener(NoRedirect())
    def access(op, **fields):
        return request(opener, origin, "/developers/access", share, {"op": op, **fields})

    status = access("read")
    identity = hashlib.sha256((origin + "|" + share).encode()).hexdigest()[:24]
    directory = base_dir.expanduser() / identity
    directory.mkdir(parents=True, mode=0o700, exist_ok=True)
    if os.name == "posix" and (directory.is_symlink() or directory.stat().st_uid != os.getuid()
                              or directory.stat().st_mode & 0o077):
        raise IntegrationError("请选择仅当前用户可访问的配置目录。")
    spec = request(opener, origin, "/developers/openapi.json", share)
    write_json(directory / "openapi.json", spec)
    print(f"应用 OpenAPI 已保存到 {directory / 'openapi.json'}")
    if docs_only or not status["app"]:
        print("已完成文档接入。")
        return

    config_path = directory / "connection.json"
    if config_path.exists():
        key = json.loads(config_path.read_bytes())
    else:
        proof = directory / "claim-proof"
        private_write(proof, secrets.token_hex(32).encode(), create_only=True)
        key = access("claim", claim_secret=proof.read_text().strip())
        if (key["app"], key["key_id"]) != (status["app"], status["key_id"]):
            raise IntegrationError("签发结果与所选应用不一致。")
        write_json(config_path, {"base_url": origin, "app": key["app"],
                                 "key_id": key["key_id"], "token": key["token"]})
        proof.unlink(missing_ok=True)
    spaces = request(opener, origin, "/v1/spaces", key["token"], {"limit": 1, "include_access": True})
    if not spaces["items"]:
        raise IntegrationError(f"密钥已保存至 {config_path}。当前应用的空间授权为空。")
    space = spaces["items"][0]
    scope = space["access"]
    if isinstance(scope, dict):
        cmd = {"op": "query", "selection": {"table": scope["projection"]["table"]}, "limit": 1}
    else:
        cmd = {"op": "list_tables", "limit": 1}
    enterprise, space_id = (quote(space[k], safe="") for k in ("enterprise", "space"))
    path = f"/v1/enterprises/{enterprise}/spaces/{space_id}/commands"
    request(opener, origin, path, key["token"], cmd)
    print(f"已验证 {key['app']} 在 {enterprise}/{space_id} 的首次读取（{cmd['op']}）。")
    print(f"应用连接配置保存在 {config_path}。请在服务端保管 token。")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--directory", type=Path, default=Path.home() / ".config/jingwei/connections",
                        help="本机私有配置目录")
    parser.add_argument("--docs-only", action="store_true", help="只下载应用 OpenAPI")
    args = parser.parse_args()
    link = getpass.getpass("粘贴完整分享链接（输入不回显）：") if sys.stdin.isatty() else sys.stdin.readline()
    try:
        connect(link, args.directory, args.docs_only)
    except IntegrationError as exc:
        sys.exit(str(exc))
    except (ValueError, KeyError, OSError, URLError):
        sys.exit("连接、证书、文件或返回格式异常，请检查本机网络和权限后使用原链接与同一配置目录重试。")


if __name__ == "__main__":
    main()
