#!/usr/bin/env python3
"""BoardRepo desktop OAuth and snapshot example. Python 3.10+, standard library only."""
import argparse
import base64
import hashlib
import http.server
import io
import json
import os
from pathlib import Path, PurePosixPath
import secrets
import shutil
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
import zipfile


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise RuntimeError("Unexpected redirect; credentials were not forwarded.")


def request(url, data=None, headers=None, method=None):
    req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
    with urllib.request.build_opener(NoRedirect).open(req, timeout=120) as response:
        return response.read(384 * 1024 * 1024 + 1)


def api(args, path, body=None):
    headers = {"Authorization": "Bearer " + args.token}
    data = None
    if body is not None:
        headers.update({"Content-Type": "application/json", "X-BoardRepo-Upload-Archive-Protocol": "2",
                        "X-BoardRepo-Change-Request-Protocol": "1"})
        data = json.dumps(body).encode()
    return json.loads(request(args.origin + "/api/v1" + path, data, headers))


def paths(files):
    seen = set()
    for name in files:
        parts = name.split("/")
        if any(part in ("", ".", "..", "__proto__") for part in parts) or \
                "\\" in name or ":" in name or any(ord(c) < 32 for c in name):
            raise RuntimeError("Unsafe project path: " + name)
        normalized = name.casefold()
        if normalized in seen:
            raise RuntimeError("Colliding project path: " + name)
        seen.add(normalized)
    if not seen or len(seen) > 10000:
        raise RuntimeError("A snapshot requires 1 to 10,000 files.")


def connect(args):
    verifier = secrets.token_urlsafe(32)
    challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")
    state = secrets.token_urlsafe(32)
    result = {}
    class Callback(http.server.BaseHTTPRequestHandler):
        def do_GET(self):
            url = urllib.parse.urlsplit(self.path)
            query = urllib.parse.parse_qs(url.query)
            if url.path != "/callback" or query.get("state") != [state] or len(query.get("code", [])) > 1 or \
                    ("iss" in query and query["iss"] != [args.origin]):
                self.send_error(400, "Invalid connection callback")
                return
            result.update(query)
            self.send_response(200)
            self.send_header("Content-Type", "text/plain; charset=utf-8")
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            self.wfile.write(b"Return to the desktop example to finish connecting.")
        def log_message(self, *unused):
            pass  # Authorization codes must not enter request logs.
    # Register this exact callback in the pilot. Configurable fixed port avoids a wildcard callback.
    with http.server.HTTPServer(("127.0.0.1", args.port), Callback) as server:
        redirect = f"http://127.0.0.1:{args.port}/callback"
        url = args.origin + "/oauth/authorize?" + urllib.parse.urlencode({
            "client_id": args.client_id, "redirect_uri": redirect, "response_type": "code", "state": state,
            "scope": "project:read project:write", "resource": args.origin + "/api/v1",
            "code_challenge": challenge, "code_challenge_method": "S256"})
        print("Open Connect BoardRepo in your browser. The example does not ask for a client secret.")
        webbrowser.open(url)
        server.timeout = 1
        deadline = time.monotonic() + 300
        while not result and time.monotonic() < deadline:
            server.handle_request()
    if result.get("error") or not result.get("code"):
        raise RuntimeError("Connection was denied or expired. Start Connect again.")
    token = json.loads(request(args.origin + "/oauth/token", urllib.parse.urlencode({
        "grant_type": "authorization_code", "client_id": args.client_id, "code": result["code"][0],
        "redirect_uri": redirect, "code_verifier": verifier}).encode(),
        {"Content-Type": "application/x-www-form-urlencoded"}))
    args.token_file.parent.mkdir(parents=True, exist_ok=True)
    descriptor = os.open(args.token_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0), 0o600)
    os.fchmod(descriptor, 0o600)
    with os.fdopen(descriptor, "w") as output:
        json.dump({"origin": args.origin, "token": token["access_token"]}, output)
    print("Connected for 30 days. Use an OS keychain in your production desktop integration.")


def pull(args):
    board = api(args, "/projects/" + args.board)
    version = args.version or board["headVersionId"]
    manifest = api(args, f"/projects/{args.board}/versions/{version}/manifest")
    paths([file["path"] for file in manifest["files"]])
    pairs = sorted([[file["path"], file["blobSha"]] for file in manifest["files"]], key=lambda pair: pair[0].encode())
    digest = hashlib.sha256(json.dumps(pairs, ensure_ascii=False, separators=(",", ":")).encode()).hexdigest()
    if digest != manifest["manifestDigest"]:
        raise RuntimeError("Manifest integrity check failed")
    target = Path(args.folder).absolute()
    if target.exists():
        raise RuntimeError("Pull into a new folder so existing files cannot be overwritten.")
    target.parent.mkdir(parents=True, exist_ok=True)
    temporary = Path(tempfile.mkdtemp(prefix=".boardrepo-pull-", dir=target.parent))
    try:
        for file in manifest["files"]:
            data = request(args.origin + f'/api/v1/projects/{args.board}/blobs/{file["blobSha"]}', headers={"Authorization": "Bearer " + args.token})
            if len(data) != file["bytes"] or hashlib.sha256(data).hexdigest() != file["blobSha"]:
                raise RuntimeError("File integrity check failed: " + file["path"])
            output = temporary.joinpath(*PurePosixPath(file["path"]).parts)
            output.parent.mkdir(parents=True, exist_ok=True)
            output.write_bytes(data)
            print("Pulled", file["path"])
        temporary.rename(target)
        # Keep the baseline outside the project, so it never becomes an uploaded source file.
        Path(args.baseline).write_text(json.dumps({"projectId": args.board, "versionId": version}))
    finally:
        if temporary.exists():
            shutil.rmtree(temporary)


def package(folder):
    root = Path(folder)
    files = sorted([path for path in root.rglob("*") if path.is_file() and not path.is_symlink()])
    names = [path.relative_to(root).as_posix() for path in files]
    paths(names)
    if any(path.stat().st_size > 256 * 1024 * 1024 for path in files) or sum(path.stat().st_size for path in files) > 384 * 1024 * 1024:
        raise RuntimeError("Project files exceed the documented snapshot limits")
    output = io.BytesIO()
    with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as archive:
        for path, name in zip(files, names):
            archive.writestr(zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)), path.read_bytes())
    return output.getvalue()


def saved_version(args, saved, project_id=None):
    project_id = saved.get("projectId", project_id)
    if not project_id or not saved.get("versionId"):
        raise RuntimeError("Invalid saved-version response. Recover with the operation key.")
    Path(args.baseline).write_text(json.dumps({"projectId": project_id, "versionId": saved["versionId"]}))
    print(json.dumps(saved, indent=2))


def publish(args):
    archive = package(args.folder)
    base = json.loads(Path(args.baseline).read_text()) if args.command == "push" else None
    common = {"idempotencyKey": args.key, "message": args.message}
    if base:
        project = base["projectId"]
        common.update({"policyHash": api(args, f"/projects/{project}/upload-policy")["hash"], "expectedParentVersionId": base["versionId"]})
        prefix = f"/projects/{project}"
        extra = {}
    else:
        owners = api(args, "/me")["ownerPrincipals"]
        owner = next(owner for owner in owners if owner["id"] == args.owner)
        common.update({"ownerPrincipalId": args.owner, "policyHash": owner["uploadPolicy"]["hash"]})
        prefix = ""
        extra = {"name": args.name, "originalFilename": "boardrepo-sync.zip"}
    stage = api(args, prefix + "/uploads", {**common, **extra, "expectedBytes": len(archive), "contentHash": hashlib.sha256(archive).hexdigest()})
    intent = {**common, "uploadId": stage["uploadId"]}
    Path(args.recovery).write_text(json.dumps({"path": prefix + "/versions" if base else "/projects", "body": intent, "projectId": base["projectId"] if base else None}))
    print("Uploading", len(archive), "bytes. Recovery intent saved before publication.")
    try:
        request(stage["url"], archive, stage["headers"], "PUT")  # No OAuth credential goes to storage.
    except urllib.error.HTTPError as error:
        if error.code != 412:
            raise
    saved = api(args, prefix + "/versions" if base else "/projects", intent)
    saved_version(args, saved, base["projectId"] if base else None)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--origin", default="https://boardrepo.com")
    parser.add_argument("--client-id")
    parser.add_argument("--port", type=int, default=4314)
    parser.add_argument("--token-file", type=Path, default=Path.home() / ".config/boardrepo-example/token.json")
    parser.add_argument("--baseline", default="boardrepo-baseline.json", help="Keep this outside the uploaded project folder")
    parser.add_argument("--recovery", default="boardrepo-recovery.json", help="Keep this outside the uploaded project folder")
    commands = parser.add_subparsers(dest="command", required=True)
    commands.add_parser("connect")
    commands.add_parser("list")
    download = commands.add_parser("pull")
    download.add_argument("board"); download.add_argument("folder"); download.add_argument("--version")
    for name in ("create", "push"):
        action = commands.add_parser(name)
        action.add_argument("folder"); action.add_argument("--key", required=True, help="Reuse for the same logical request")
        action.add_argument("--message", default="")
        if name == "create":
            action.add_argument("--name", required=True); action.add_argument("--owner", required=True)
    op = commands.add_parser("operation"); op.add_argument("key")
    commands.add_parser("resume"); commands.add_parser("disconnect")
    args = parser.parse_args()
    url = urllib.parse.urlsplit(args.origin)
    if url.username or url.password or url.path not in ("", "/") or url.query or url.fragment or \
            (url.scheme != "https" and not (url.scheme == "http" and url.hostname in ("localhost", "127.0.0.1"))):
        raise RuntimeError("Use HTTPS or local HTTP loopback for BoardRepo.")
    args.origin = args.origin.rstrip("/")
    if args.command == "connect":
        if not args.client_id:
            parser.error("connect requires --client-id")
        return connect(args)
    stored = json.loads(args.token_file.read_text())
    if stored["origin"] != args.origin:
        raise RuntimeError("This token belongs to another BoardRepo origin")
    args.token = stored["token"]
    if args.command == "list": print(json.dumps(api(args, "/projects"), indent=2)); print(json.dumps(api(args, "/me"), indent=2))
    elif args.command == "pull": pull(args)
    elif args.command in ("push", "create"): publish(args)
    elif args.command == "operation": print(json.dumps(api(args, "/operations/" + urllib.parse.quote(args.key, safe="")), indent=2))
    elif args.command == "resume":
        intent = json.loads(Path(args.recovery).read_text())
        project_id = intent.get("projectId")
        if not project_id and intent["path"].startswith("/projects/") and intent["path"].endswith("/versions"):
            project_id = intent["path"].split("/")[2]
        saved_version(args, api(args, intent["path"], intent["body"]), project_id)
    elif args.command == "disconnect":
        request(args.origin + "/oauth/revoke", urllib.parse.urlencode({"token": args.token}).encode(), {"Content-Type": "application/x-www-form-urlencoded"})
        args.token_file.unlink(); print("Disconnected")


if __name__ == "__main__":
    try:
        main()
    except urllib.error.HTTPError as error:
        print(error.code, error.read().decode())
        print("For 401, reconnect. For head_moved, Pull and reconcile. After a lost response, inspect operation or resume the saved intent.")
        raise SystemExit(1)
