# -*- coding: utf-8 -*-
"""Publish the PayGo file to a self-hosted figcraft-server and print its links.

    python publish.py wss://figcraft.coordenadas.co/?key=<server key>

Optional:
    --file  <path>   a different .figcraft (default: the PayGo file next door)
    --name  <name>   the file's name on the server (default: its document name)
    --share          also start sharing, which produces the join codes

Runs through `figcraft-cli mcp` with no automation roots — the roots confine file access but
also switch the network off, and publishing needs the network.
"""
import argparse
import json
import os
import sys
import time

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                "..", "_build"))
from mcp_client import connect                                  # noqa: E402

HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_FILE = os.path.abspath(os.path.join(HERE, "..", "PayGo App Design.figcraft"))


def wait_live(m, tries=40, delay=3):
    """collab.publish returns while still "connecting"; poll until it settles."""
    for _ in range(tries):
        time.sleep(delay)
        p = m.tool("run_command", {"command": "collab.peers", "params": {}})
        if not isinstance(p, dict):
            continue
        status = p.get("status")
        if status == "live":
            return p
        if status == "failed":
            raise SystemExit("server refused the file: %s" % (p.get("reason"),))
        print("  ...%s" % status)
    raise SystemExit("timed out waiting for the server")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("server", help="wss://host/?key=<server key>  (or ws://host:47900/?key=…)")
    ap.add_argument("--file", default=DEFAULT_FILE)
    ap.add_argument("--name")
    ap.add_argument("--share", action="store_true",
                    help="also start sharing, to get the join codes")
    a = ap.parse_args()

    m = connect()                       # no automation roots: the network stays on
    try:
        opened = m.tool("open_file", {"path": os.path.abspath(a.file)})
        summary = opened.get("opened", {}).get("summary", {}) if isinstance(opened, dict) else {}
        print("opened %s — %s pages, %s layers"
              % (summary.get("name"), summary.get("pages"), summary.get("layers")))

        base = a.server.split("?", 1)[0].rstrip("/") + "/"
        info = m.tool("run_command", {"command": "collab.serverInfo",
                                      "params": {"server": base}})
        print("server:", json.dumps(info))

        params = {"server": a.server}
        if a.name:
            params["name"] = a.name
        m.tool("run_command", {"command": "collab.publish", "params": params})
        peers = wait_live(m)

        pub = peers.get("published") or {}
        print("\n  file:  %s" % pub.get("file"))
        print("  edit:  %s" % pub.get("edit"))
        print("  view:  %s" % pub.get("view"))
        if pub.get("owner"):
            print("  owner token (shown once): %s" % pub["owner"])

        if a.share:
            m.tool("run_command", {"command": "collab.share",
                                   "params": {"via": "online", "access": "view"}})
            peers = wait_live(m)
            sh = peers.get("share") or {}
            print("\n  view code:  %s" % sh.get("viewCode"))
            print("  view link:  %s" % sh.get("viewLink"))
            print("  edit code:  %s" % sh.get("editCode"))
            print("  edit link:  %s" % sh.get("editLink"))

        print("\nPoint the app's default at it too:")
        print('  figcraft-cli run <(echo \'[{"command":"pref.publishServer",'
              '"params":{"url":"%s"}}]\')' % base)
    finally:
        m.close()


if __name__ == "__main__":
    main()
