#!/usr/bin/env python3
"""
开灵API中台 · 工商银行农产品收购付款即开票(业务接口)—— 示例公共模块(只用 Python 3.6+ 标准库)

环境变量(凭据和测试资料一律从环境变量读,脚本里不写死):
  KL_APP_KEY / KL_APP_SECRET   开灵签发的调用凭据(测试凭据向开灵索取)
  KL_BASE                      默认 https://openapi.kailingteck.com
  KL_PREFIX                    你自己的单号前缀(测试环境数据各家共用),默认 KLT
  KL_FARMER_ID / KL_FARMER_NAME / KL_FARMER_IDNO / KL_FARMER_CARD / KL_FARMER_MOBILE   测试农户(向开灵索取)
  KL_FARMER_ICBC_CARD          测试农户的卡是不是工商银行的卡(1 是,测试农户是)
  KL_FARMER_ID_START / KL_FARMER_ID_END   测试农户身份证签发 / 截止日期(yyyy-MM-dd,截止可填「长期」)
  KL_RECORD_DIR                设了就把请求和返回(个人信息脱敏后)存成运行记录
"""
import hashlib, json, os, re, sys, time, urllib.error, urllib.request

BASE = os.environ.get("KL_BASE", "https://openapi.kailingteck.com").rstrip("/")
APP_KEY = os.environ.get("KL_APP_KEY", "")
APP_SECRET = os.environ.get("KL_APP_SECRET", "")
PREFIX = os.environ.get("KL_PREFIX", "KLT")

FARMER = {
    "farmerId": os.environ.get("KL_FARMER_ID", ""),
    "name": os.environ.get("KL_FARMER_NAME", ""),
    "idNo": os.environ.get("KL_FARMER_IDNO", ""),
    "phone": os.environ.get("KL_FARMER_MOBILE", ""),
    "bankCard": os.environ.get("KL_FARMER_CARD", ""),
    "isIcbcCard": os.environ.get("KL_FARMER_ICBC_CARD", "") in ("1", "true"),   # 测试农户的卡是工行卡,设 1
    "idStartDate": os.environ.get("KL_FARMER_ID_START", "2016-01-01"),
    "idEndDate": os.environ.get("KL_FARMER_ID_END", "长期"),
    "address": os.environ.get("KL_FARMER_ADDRESS", "河北省石家庄市测试路1号"),
}


# ==== 接入包摘录:开始 ====
def call(path, body):
    """调中台业务接口:path 如 'farmer/status';返回完整外壳 dict。HTTP 4xx/5xx 也带外壳 JSON,照样解析。"""
    raw = json.dumps(body, ensure_ascii=False, separators=(",", ":"))
    ts = str(int(time.time()))
    sign = hashlib.sha256((APP_KEY + ts + raw + APP_SECRET).encode("utf-8")).hexdigest()
    req = urllib.request.Request(BASE + "/api/v1/icbc-agri/" + path, data=raw.encode("utf-8"), method="POST", headers={
        "Content-Type": "application/json", "X-App-Key": APP_KEY, "X-Timestamp": ts, "X-Sign": sign})
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            http, text = r.status, r.read().decode("utf-8")
    except urllib.error.HTTPError as e:
        http, text = e.code, e.read().decode("utf-8")
    try:
        resp = json.loads(text)
    except ValueError:
        resp = {"code": "NON_JSON", "msg": text[:200], "data": None}
    resp["_http"] = http
    return resp


def ok(resp):
    """外壳成功"""
    return resp.get("code") == "CYT_00000"


def data(resp):
    return resp.get("data") or {}
# ==== 接入包摘录:结束 ====


def need(*names):
    miss = [n for n in names if not os.environ.get(n)]
    if miss:
        sys.exit("缺少环境变量:" + "、".join(miss) + "(测试凭据和测试资料向开灵索取)")


def new_order_id(tag="PO"):
    return (PREFIX + tag + time.strftime("%y%m%d%H%M%S"))[:24]


# ---------------- 运行记录(个人信息脱敏) ----------------
_PII_KEYS = {"name", "idNo", "phone", "mobile", "bankCard", "address", "drawerName", "drawerIdNo", "payerAccount", "payerAccountName"}


def _mask(v):
    s = str(v)
    if len(s) <= 4:
        return s[:1] + "*" * (len(s) - 1)
    return s[:2] + "*" * (len(s) - 4) + s[-2:]


def scrub(o, top=True):
    """只脱请求体 / 返回顶层的个人信息字段(农户姓名、身份证、手机号、卡号、住址,开票员),收购明细里的品名不动"""
    if isinstance(o, dict):
        return {k: (_mask(v) if top and k in _PII_KEYS and isinstance(v, (str, int)) else scrub(v, top and k in ("data",))) for k, v in o.items()}
    if isinstance(o, list):
        return [scrub(x, False) for x in o]
    if isinstance(o, str) and "/api/v1/icbc" in o:
        return re.sub(r"(/redirect/|/file/)[A-Za-z0-9_-]+", r"\1<一次性地址>", o)
    return o


def record(name, path, body, resp, verdict="通过", notes=None, branch=False):
    d = os.environ.get("KL_RECORD_DIR")
    if not d:
        return
    d = os.path.join(d, "branches") if branch else d
    os.makedirs(d, exist_ok=True)
    r = dict(resp)
    http = r.pop("_http", 200)
    for k in ("requestId", "timestamp"):
        r.pop(k, None)
    with open(os.path.join(d, name + ".json"), "w", encoding="utf-8") as f:
        json.dump({"script": os.path.basename(sys.argv[0]), "when": time.strftime("%Y-%m-%d"), "path": "/api/v1/icbc-agri/" + path,
                   "http": http, "verdict": verdict, "req": scrub(body), "resp": scrub(r), "notes": notes or []}, f, ensure_ascii=False, indent=2)


def show(title, resp):
    d = data(resp)
    print("—— %s:HTTP %s %s %s" % (title, resp.get("_http"), resp.get("code"), d.get("status", "")), d.get("statusText", "") or d.get("hint", "") or resp.get("msg", ""))
