#!/usr/bin/env python3
"""Deploy the full HowToCook clone (~/workspace/howtocook, excluding .git)
to a NEW assets-only Worker `howtocook` (howtocook.bigfox.vip).
Adds one generated /index.html directory listing; repo files are untouched.
Usage: deploy_howtocook.py [--deploy]
Never prints tokens.
"""
import base64, hashlib, json, sys, urllib.request, urllib.error, uuid, os, urllib.parse, html as htmlmod
sys.path.insert(0, "/opt/muse/skills/custom-connector-setup/bin")
from dynamic_credentials import add_surrogate_to_request, read_json_response

ACCOUNT = "fbf423b9aa77118601e0bea929f3b5b0"
SCRIPT = "howtocook"
BASE = "https://api.cloudflare.com/client/v4"
ROOT = os.path.expanduser("~/workspace/howtocook")

MIME = {"html":"text/html","md":"text/markdown","jpg":"image/jpeg","jpeg":"image/jpeg","png":"image/png",
        "webp":"image/webp","svg":"image/svg+xml","json":"application/json","yml":"text/yaml","yaml":"text/yaml",
        "js":"text/javascript","css":"text/css","txt":"text/plain","gif":"image/gif","sample":"text/plain",
        "toml":"text/plain","xml":"text/xml","csv":"text/csv","mp4":"video/mp4"}

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args):
        raise RuntimeError("redirect refused")

def opener():
    return urllib.request.build_opener(NoRedirect())

def req_json(method, path, body=None):
    data = json.dumps(body).encode() if body is not None else None
    headers = {"Content-Type": "application/json"}
    r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
    add_surrogate_to_request(r, "custom.cloudflare", allowed_hosts=["api.cloudflare.com"])
    try:
        with opener().open(r, timeout=60) as resp:
            return resp.status, read_json_response(resp)
    except urllib.error.HTTPError as e:
        raw = e.read().decode(errors="replace")
        try:
            return e.code, json.loads(raw)
        except Exception:
            return e.code, {"raw": raw[:2000]}

def multipart(parts):
    boundary = "----cfdeploy" + uuid.uuid4().hex
    out = b""
    for name, filename, ctype, data in parts:
        out += f"--{boundary}\r\n".encode()
        disp = f'Content-Disposition: form-data; name="{name}"'
        if filename:
            disp += f'; filename="{filename}"'
        out += (disp + "\r\n").encode()
        if ctype:
            out += f"Content-Type: {ctype}\r\n".encode()
        out += b"\r\n" + data + b"\r\n"
    out += f"--{boundary}--\r\n".encode()
    return boundary, out

def req_multipart(method, path, parts, auth="surrogate", jwt=None):
    boundary, data = multipart(parts)
    headers = {"Content-Type": f"multipart/form-data; boundary={boundary}"}
    r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
    if auth == "surrogate":
        add_surrogate_to_request(r, "custom.cloudflare", allowed_hosts=["api.cloudflare.com"])
    elif auth == "jwt":
        r.add_header("Authorization", f"Bearer {jwt}")
    try:
        with opener().open(r, timeout=300) as resp:
            raw = resp.read()
            try:
                return resp.status, json.loads(raw.decode())
            except Exception:
                return resp.status, {"raw": raw[:2000].decode(errors="replace")}
    except urllib.error.HTTPError as e:
        raw = e.read().decode(errors="replace")
        try:
            return e.code, json.loads(raw)
        except Exception:
            return e.code, {"raw": raw[:2000]}

def build_index(paths):
    groups = {}
    for p in paths:
        top = p.split("/")[1] if p.count("/") > 1 else "(root)"
        groups.setdefault(top, []).append(p)
    out = ["<!DOCTYPE html><html lang='zh-CN'><head><meta charset='utf-8'>",
           "<meta name='viewport' content='width=device-width,initial-scale=1'>",
           "<title>HowToCook 全量镜像（暂未启用）</title>",
           "<style>body{font-family:system-ui;max-width:900px;margin:24px auto;padding:0 16px;line-height:1.7}",
           "h1{font-size:24px}h2{margin-top:28px;font-size:19px}li{margin:2px 0}a{color:#2E6B34}</style></head><body>",
           "<h1>HowToCook 全量镜像</h1><p>来源：GitHub Anduin2017/HowToCook。此处为整仓原样存放，尚未接入菜谱网站。</p>"]
    for top in sorted(groups):
        out.append(f"<h2>{htmlmod.escape(top)}（{len(groups[top])}）</h2><ul>")
        for p in sorted(groups[top]):
            href = urllib.parse.quote(p)
            out.append(f"<li><a href='{href}'>{htmlmod.escape(p[1:])}</a></li>")
        out.append("</ul>")
    out.append("</body></html>")
    return "".join(out).encode("utf-8")

def main():
    do_deploy = "--deploy" in sys.argv
    files = {}  # path -> (content_bytes, ext)
    for dirpath, dirnames, filenames in os.walk(ROOT):
        if ".git" in dirnames:
            dirnames.remove(".git")
        for fn in filenames:
            full = os.path.join(dirpath, fn)
            rel = "/" + os.path.relpath(full, ROOT).replace(os.sep, "/")
            ext = fn.rsplit(".", 1)[-1].lower() if "." in fn else "txt"
            with open(full, "rb") as f:
                files[rel] = (f.read(), ext)
    files["/index.html"] = (build_index(list(files.keys())), "html")
    print(f"files: {len(files)} total_bytes: {sum(len(c) for c,_ in files.values())}")

    manifest = {}
    for path, (content, ext) in files.items():
        h = hashlib.sha256(base64.b64encode(content) + ext.encode()).hexdigest()[:32]
        manifest[path] = {"hash": h, "size": len(content)}

    status, sess = req_json("POST", f"/accounts/{ACCOUNT}/workers/scripts/{SCRIPT}/assets-upload-session",
                            {"manifest": manifest})
    print("session_status", status, "success", sess.get("success"))
    if not sess.get("success"):
        print(json.dumps(sess)[:3000]); sys.exit(2)
    jwt = sess["result"]["jwt"]
    buckets = sess["result"].get("buckets") or []
    print("buckets:", len(buckets))
    completion = jwt
    by_hash = {manifest[p]["hash"]: (c, MIME.get(e, "application/octet-stream")) for p, (c, e) in files.items()}
    for i, bucket in enumerate(buckets):
        parts = [(h, None, by_hash[h][1], base64.b64encode(by_hash[h][0])) for h in bucket]
        st, up = req_multipart("POST", "/accounts/" + ACCOUNT + "/workers/assets/upload?base64=true", parts, auth="jwt", jwt=jwt)
        ok = isinstance(up, dict) and up.get("success")
        print(f"bucket {i+1}/{len(buckets)} status {st} success {ok}")
        if isinstance(up, dict) and up.get("result") and up["result"].get("jwt"):
            completion = up["result"]["jwt"]
        elif st not in (200, 201, 202):
            print(json.dumps(up)[:2000]); sys.exit(3)
    print("asset_upload_done")

    metadata = {
        "assets": {"jwt": completion, "config": {"html_handling": "auto-trailing-slash", "not_found_handling": "none", "serve_directly": True}},
        "compatibility_date": "2026-11-23",
    }
    parts = [("metadata", None, "application/json", json.dumps(metadata).encode())]
    st, ver = req_multipart("POST", f"/accounts/{ACCOUNT}/workers/scripts/{SCRIPT}/versions", parts, auth="surrogate")
    print("version_status", st, "success", ver.get("success") if isinstance(ver, dict) else None)
    if not (isinstance(ver, dict) and ver.get("success")):
        print(json.dumps(ver)[:3000]); sys.exit(4)
    vid = ver["result"]["id"]
    print("version_id", vid)

    if do_deploy:
        st, dep = req_json("POST", f"/accounts/{ACCOUNT}/workers/scripts/{SCRIPT}/deployments",
                           {"strategy": "percentage", "versions": [{"version_id": vid, "percentage": 100}],
                            "annotations": {"workers/message": "Deploy HowToCook full clone (parked, unused)"}})
        print("deploy_status", st, "success", dep.get("success") if isinstance(dep, dict) else None)
        if not (isinstance(dep, dict) and dep.get("success")):
            print(json.dumps(dep)[:3000]); sys.exit(5)
        print("deployment done")
    else:
        print("not_deployed (trial)")

if __name__ == "__main__":
    main()
