#!/usr/bin/env python3
"""SemiBox production management CLI.

A deployment is: this checkout, a generated docker-compose.yml, and a container
serving the static build through nginx.

    ./semibox-cli configure    # ask some questions, write docker-compose.yml
    ./semibox-cli up           # start (detached); builds if needed
    ./semibox-cli update       # git pull, rebuild if anything changed, restart
    ./semibox-cli down         # stop
    ./semibox-cli restart      # restart the web service
    ./semibox-cli status       # container state + health endpoint check
    ./semibox-cli logs [-f]    # web server logs
    ./semibox-cli version      # app version + git revision

With multiplayer, the same tool runs the door:

    ./semibox-cli accounts     # who has an account
    ./semibox-cli invite --uses 5 --note "for the tuesday crowd"
    ./semibox-cli ban someone "spawning junk"
    ./semibox-cli operator someone

The compose file is *generated* and gitignored. That is the point: a server can
`git pull` forever without its own deployment config being touched, and this
repo never ships a docker-compose.yml that collides with somebody else's.

Two deployment shapes are supported:

  proxy   The container joins an existing nginx-proxy network and announces
          itself with VIRTUAL_HOST. jwilder/nginx-proxy routes to it and
          acme-companion gets it a certificate. No published ports.
  port    The container publishes a port on the host and you point whatever
          you like at it.
"""

import argparse
import json
import os
import shutil
import subprocess
import sys
import urllib.error
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parent
COMPOSE_FILE = ROOT / "docker-compose.yml"
# Bumped whenever a generated compose file would be *wrong* against the current
# repo rather than merely out of date. `up` and `update` warn below this.
COMPOSE_GENERATION = 4
SETTINGS_FILE = ROOT / ".semibox-deploy.json"

CYAN, GREEN, RED, YELLOW, DIM, RESET = (
    "\033[36m",
    "\033[32m",
    "\033[31m",
    "\033[33m",
    "\033[2m",
    "\033[0m",
)


def engine() -> str:
    found = shutil.which("docker") or shutil.which("podman")
    if not found:
        sys.exit(f"{RED}error{RESET}: neither docker nor podman found on PATH")
    return found


def sh(*cmd: str, capture: bool = False, quiet: bool = False) -> subprocess.CompletedProcess:
    if not capture and not quiet:
        print(f"{CYAN}→ {' '.join(cmd)}{RESET}", flush=True)
    return subprocess.run(list(cmd), cwd=ROOT, capture_output=capture, text=True)


def compose(*args: str, capture: bool = False, quiet: bool = False) -> subprocess.CompletedProcess:
    if not COMPOSE_FILE.exists():
        sys.exit(
            f"{RED}error{RESET}: no docker-compose.yml here.\n"
            f"  Run {CYAN}./semibox-cli configure{RESET} first — it writes one."
        )
    return sh(engine(), "compose", *args, capture=capture, quiet=quiet)


# ── configuration ───────────────────────────────────────────────────────────

DEFAULTS = {
    "mode": "proxy",
    "multiplayer": False,
    "accounts": "invite",
    "domain": "",
    "email": "",
    "network": "nginx-proxy",
    "letsencrypt": True,
    "port": 8080,
    "container_name": "semibox",
    "project": "semibox",
}


def load_settings() -> dict:
    settings = dict(DEFAULTS)
    if SETTINGS_FILE.exists():
        try:
            settings.update(json.loads(SETTINGS_FILE.read_text()))
        except json.JSONDecodeError:
            print(f"{YELLOW}warning{RESET}: {SETTINGS_FILE.name} is not valid JSON; ignoring it")
    return settings


def existing_networks() -> list[str]:
    """Networks docker already knows about — most likely one is the proxy's."""
    result = sh(engine(), "network", "ls", "--format", "{{.Name}}", capture=True)
    if result.returncode != 0:
        return []
    skip = {"bridge", "host", "none"}
    return [n for n in result.stdout.split() if n not in skip]


def ask(prompt: str, default: str, choices: list[str] | None = None) -> str:
    hint = f" [{'/'.join(choices)}]" if choices else ""
    shown = f" ({default})" if default else ""
    while True:
        answer = input(f"{prompt}{hint}{shown}: ").strip() or default
        if choices and answer not in choices:
            print(f"  {RED}pick one of{RESET} {', '.join(choices)}")
            continue
        return answer


def ask_yes(prompt: str, default: bool) -> bool:
    answer = input(f"{prompt} [{'Y/n' if default else 'y/N'}]: ").strip().lower()
    return default if not answer else answer.startswith("y")


def configure(args: argparse.Namespace) -> None:
    settings = load_settings()
    interactive = not args.non_interactive

    # Flags win over saved answers, saved answers win over defaults.
    for key in ("mode", "domain", "email", "network", "container_name", "project"):
        value = getattr(args, key, None)
        if value:
            settings[key] = value
    if args.port:
        settings["port"] = args.port
    if getattr(args, "data_dir", None) is not None:
        # "" (or --no-data-dir) goes back to the named volume
        settings["data_dir"] = args.data_dir or ""
    if args.no_letsencrypt:
        settings["letsencrypt"] = False
    if args.multiplayer:
        settings["multiplayer"] = True
    if args.no_multiplayer:
        settings["multiplayer"] = False
    if getattr(args, "accounts", None):
        settings["accounts"] = args.accounts

    if interactive:
        print(f"{DIM}Answers are saved to {SETTINGS_FILE.name}; re-run any time.{RESET}\n")
        settings["mode"] = ask(
            "Serve behind an nginx-proxy, or publish a port directly",
            settings["mode"],
            ["proxy", "port"],
        )
        if settings["mode"] == "proxy":
            found = existing_networks()
            if found:
                print(f"{DIM}  networks found: {', '.join(found)}{RESET}")
            settings["network"] = ask("  Proxy network to join", settings["network"])
            settings["domain"] = ask("  Domain to serve (VIRTUAL_HOST)", settings["domain"])
            while not settings["domain"]:
                print(f"  {RED}a domain is required for proxy mode{RESET}")
                settings["domain"] = ask("  Domain to serve (VIRTUAL_HOST)", "")
            settings["letsencrypt"] = ask_yes(
                "  Request a Let's Encrypt certificate (acme-companion)",
                settings["letsencrypt"],
            )
            if settings["letsencrypt"]:
                settings["email"] = ask("  Contact email for the certificate", settings["email"])
        else:
            settings["port"] = int(ask("  Host port to publish", str(settings["port"])))
        settings["container_name"] = ask("Container name", settings["container_name"])
        settings["multiplayer"] = ask_yes(
            "Run the multiplayer session server (ADR 0012)",
            settings["multiplayer"],
        )
        if settings["multiplayer"]:
            # Anything on the public internet wants a door. `invite` is the
            # default because a public sandbox with no door is a public sandbox
            # full of somebody else's junk.
            print(f"{DIM}  off: anyone may play · open: anyone may sign up{RESET}")
            print(f"{DIM}  invite: sign-ups need a code · closed: no new accounts{RESET}")
            settings["accounts"] = ask(
                "  Accounts",
                settings.get("accounts", "invite"),
                ["off", "open", "invite", "closed"],
            )

    if settings["mode"] == "proxy" and not settings["domain"]:
        sys.exit(f"{RED}error{RESET}: proxy mode needs --domain")

    SETTINGS_FILE.write_text(json.dumps(settings, indent=2) + "\n")
    COMPOSE_FILE.write_text(render_compose(settings))

    print(f"\n{GREEN}wrote{RESET} {COMPOSE_FILE.name} {DIM}(gitignored){RESET}")
    print(f"{GREEN}wrote{RESET} {SETTINGS_FILE.name} {DIM}(gitignored){RESET}")
    if settings["mode"] == "proxy":
        print(
            f"\nMake sure the {CYAN}{settings['network']}{RESET} network exists and your proxy is on it:"
            f"\n  {DIM}docker network create {settings['network']}{RESET}"
        )
        scheme = "https" if settings["letsencrypt"] else "http"
        print(f"\nThen {CYAN}./semibox-cli up{RESET} → {scheme}://{settings['domain']}")
    else:
        print(f"\nThen {CYAN}./semibox-cli up{RESET} → http://localhost:{settings['port']}")


def render_compose(s: dict) -> str:
    """Generate the compose file. Plain string building — no YAML dependency."""
    lines = [
        "# Generated by ./semibox-cli configure — edit that, not this.",
        "# Regenerating overwrites this file. It is gitignored, so `git pull`",
        "# will never touch it.",
        f"# semibox-compose-generation: {COMPOSE_GENERATION}",
        f"name: {s['project']}",
        "",
        "services:",
        "  web:",
        "    build:",
        "      context: .",
        "      target: web",
        "    image: semibox:latest",
        f"    container_name: {s['container_name']}",
        "    restart: unless-stopped",
        # Neither image needs to gain privileges after start (nginx drops to
        # its worker user itself, the session server starts as `node`).
        "    security_opt:",
        "      - no-new-privileges:true",
    ]

    if s["mode"] == "proxy":
        env = [
            f"      VIRTUAL_HOST: {s['domain']}",
            "      VIRTUAL_PORT: \"80\"",
        ]
        if s["letsencrypt"]:
            env.append(f"      LETSENCRYPT_HOST: {s['domain']}")
            if s["email"]:
                env.append(f"      LETSENCRYPT_EMAIL: {s['email']}")
        lines += [
            "    # No published ports: the proxy reaches this over the shared",
            "    # network, so nothing needs to be open on the host.",
            "    expose:",
            "      - \"80\"",
            "    environment:",
            *env,
            "    networks:",
            "      - proxy",
            # With multiplayer on, nginx must also reach the session service,
            # which lives on the project's default network (never the proxy
            # network, where every other stack could see it).
            *(["      - default"] if s.get("multiplayer") else []),
        ]
    else:
        lines += [
            "    ports:",
            f"      - \"{s['port']}:80\"",
        ]

    lines += [
        "    healthcheck:",
        # 127.0.0.1, not localhost: /etc/hosts maps localhost to ::1 as well,
        # and a v4-only listener refuses that — a healthcheck that fails for
        # ever while the site is perfectly fine.
        "      test: [\"CMD\", \"wget\", \"-qO-\", \"http://127.0.0.1/healthz\"]",
        "      interval: 30s",
        "      timeout: 3s",
        "      retries: 3",
        "      start_period: 5s",
    ]

    if s.get("multiplayer"):
        lines += [
            "",
            "  # The session server (ADR 0012). nginx proxies /session to it, so",
            "  # multiplayer shares the site's hostname and certificate and needs",
            "  # nothing published on the host.",
            "  session:",
            "    build:",
            "      context: .",
            "      target: session",
            "    image: semibox-session:latest",
            f"    container_name: {s['container_name']}-session",
            "    restart: unless-stopped",
            "    security_opt:",
            "      - no-new-privileges:true",
            "    expose:",
            "      - \"8081\"",
            "    environment:",
            "      # off | open | invite | closed — `node server/admin.js` manages",
            "      # accounts, invites and bans inside this container.",
            f"      SEMIBOX_ACCOUNTS: {s.get('accounts', 'invite')}",
            "    # Sessions are kept here, so a restart or a redeploy does not",
            "    # throw away what a group has built.",
            "    volumes:",
            f"      - {s['data_dir']}:/data" if s.get("data_dir") else "      - sessions:/data",
            "    healthcheck:",
            "      test: [\"CMD\", \"wget\", \"-qO-\", \"http://127.0.0.1:8081/healthz\"]",
            "      interval: 30s",
            "      timeout: 3s",
            "      retries: 3",
            "      start_period: 5s",
        ]

    if s["mode"] == "proxy":
        lines += [
            "",
            "networks:",
            "  proxy:",
            "    external: true",
            f"    name: {s['network']}",
        ]

    if s.get("multiplayer") and not s.get("data_dir"):
        lines += ["", "volumes:", "  sessions:"]

    return "\n".join(lines) + "\n"


# ── operations ──────────────────────────────────────────────────────────────


def compose_generation() -> int:
    """Which generator wrote the compose file that is here, or 0 if unmarked."""
    if not COMPOSE_FILE.exists():
        return 0
    for line in COMPOSE_FILE.read_text().splitlines()[:10]:
        if line.startswith("# semibox-compose-generation:"):
            try:
                return int(line.split(":", 1)[1])
            except ValueError:
                return 0
    return 0


def warn_if_stale() -> None:
    """Say so when the compose file predates something that matters.

    Generation 2 added explicit build targets. Without one, `build: .` takes
    the Dockerfile's last stage — which is why `web` is deliberately last, so
    an unmarked file still works. This is the belt to that braces.
    """
    found = compose_generation()
    if found >= COMPOSE_GENERATION:
        return
    print(
        f"{YELLOW}note{RESET}: {COMPOSE_FILE.name} was written by an older "
        f"{CYAN}configure{RESET} (generation {found}, current {COMPOSE_GENERATION}).\n"
        f"  It should still work. To pick up newer options — multiplayer, explicit\n"
        f"  build targets — run {CYAN}./semibox-cli configure{RESET} again; your saved\n"
        f"  answers are reused, so it is a few Enters.",
        file=sys.stderr,
    )


def services() -> list[str]:
    """Which compose services this deployment runs.

    Named explicitly rather than left to `up` with no arguments, so a stale
    service in a hand-edited compose file is never started by accident.
    """
    settings = load_settings()
    return ["web", "session"] if settings.get("multiplayer") else ["web"]


def health_url() -> str:
    settings = load_settings()
    if settings["mode"] == "proxy":
        scheme = "https" if settings["letsencrypt"] else "http"
        return f"{scheme}://{settings['domain']}/healthz"
    return f"http://localhost:{settings['port']}/healthz"


def check_health() -> bool:
    url = health_url()
    try:
        with urllib.request.urlopen(url, timeout=5) as resp:
            print(f"health: {GREEN}{resp.status} {resp.read().decode().strip()}{RESET} ({url})")
            return True
    except (urllib.error.URLError, OSError) as e:
        print(f"health: {RED}unreachable{RESET} ({url}): {e}")
        return False


def head() -> str:
    return sh("git", "rev-parse", "HEAD", capture=True).stdout.strip()


def admin(*args: str) -> int:
    """Run the account admin, wherever the accounts happen to live.

    Three ways a deployment can be arranged, and the right one is guessable:
    the session container is running (the normal case), the repo is running the
    server directly with SEMIBOX_DATA set, or accounts are not on at all — in
    which case say so rather than printing an unhelpful stack trace.
    """
    settings = load_settings()
    if COMPOSE_FILE.exists() and settings.get("multiplayer"):
        running = compose("ps", "-q", "session", capture=True, quiet=True).stdout.strip()
        if running:
            return compose("exec", "-T", "session", "node", "server/admin.js", *args, quiet=True).returncode
        print(
            f"{YELLOW}note{RESET}: the session container is not running; "
            f"start it with {CYAN}./semibox-cli up{RESET}",
            file=sys.stderr,
        )
    data = os.environ.get("SEMIBOX_DATA", "")
    if not data:
        print(
            f"{RED}error{RESET}: no running session container, and SEMIBOX_DATA is not set.\n"
            f"  Accounts live in the session server's data directory. Either start it\n"
            f"  ({CYAN}./semibox-cli up{RESET}) or point SEMIBOX_DATA at the directory.",
            file=sys.stderr,
        )
        return 1
    return sh("node", str(ROOT / "server" / "admin.js"), *args, quiet=True).returncode


def update(args: argparse.Namespace) -> int:
    """Pull, and rebuild only if something actually changed.

    Safe to run from cron: it is quiet when there is nothing to do, and it
    never rebuilds an image for a commit that did not arrive.
    """
    quiet = args.quiet
    before = head()
    pull = sh("git", "pull", "--ff-only", capture=quiet, quiet=quiet)
    if pull.returncode != 0:
        if quiet:
            print(pull.stdout, pull.stderr, file=sys.stderr)
        print(f"{RED}error{RESET}: git pull failed — resolve it by hand", file=sys.stderr)
        return pull.returncode
    after = head()

    if before == after and not args.force:
        if not quiet:
            print(f"already up to date at {DIM}{after[:8]}{RESET}; nothing to do")
        return 0

    if not quiet:
        print(f"{GREEN}updating{RESET} {before[:8]} → {after[:8]}")
    warn_if_stale()
    rc = compose("up", "-d", "--build", *services(), quiet=quiet).returncode
    if rc != 0:
        return rc
    # Old layers pile up fast when rebuilding a node image on every deploy.
    sh(engine(), "image", "prune", "-f", capture=True)
    if not quiet:
        check_health()
    return 0


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="semibox-cli",
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    sub = parser.add_subparsers(dest="cmd", required=True)

    p_conf = sub.add_parser("configure", help="write docker-compose.yml for this deployment")
    p_conf.add_argument("--mode", choices=["proxy", "port"], help="behind a proxy, or publish a port")
    p_conf.add_argument("--domain", help="VIRTUAL_HOST / LETSENCRYPT_HOST")
    p_conf.add_argument("--email", help="LETSENCRYPT_EMAIL")
    p_conf.add_argument("--network", help="existing proxy network to join")
    p_conf.add_argument("--port", type=int, help="host port, for --mode port")
    p_conf.add_argument("--container-name", dest="container_name", help="container name")
    p_conf.add_argument("--project", help="compose project name")
    p_conf.add_argument("--no-letsencrypt", action="store_true", help="skip certificate variables")
    p_conf.add_argument(
        "--multiplayer", action="store_true", help="also run the session server"
    )
    p_conf.add_argument(
        "--no-multiplayer", action="store_true", help="single player only (the default)"
    )
    p_conf.add_argument(
        "--accounts",
        choices=["off", "open", "invite", "closed"],
        help="who may join a session (default: invite)",
    )
    p_conf.add_argument(
        "--data-dir",
        dest="data_dir",
        help="bind-mount this host directory as the session server's /data "
             "instead of a named volume (relative to the repo; give '' to go back "
             "to the volume). It must be writable by uid 1000 (node).",
    )
    p_conf.add_argument(
        "-y", "--non-interactive", action="store_true", help="use flags and saved answers only"
    )

    sub.add_parser("up", help="start the web service (detached)")
    sub.add_parser("down", help="stop all services")
    sub.add_parser("restart", help="restart the web service")
    sub.add_parser("status", help="show container state and health")
    p_up = sub.add_parser("update", help="git pull, rebuild if changed, restart")
    p_up.add_argument("--force", action="store_true", help="rebuild even with no new commits")
    p_up.add_argument("-q", "--quiet", action="store_true", help="only speak up on change or error")
    p_logs = sub.add_parser("logs", help="show web service logs")
    p_logs.add_argument("-f", "--follow", action="store_true")
    sub.add_parser("version", help="show app version and git revision")

    # — accounts —
    #
    # Thin wrappers around `server/admin.js` inside the session container, so
    # the deployment tool is one thing to remember rather than two. The script
    # itself stays the implementation: it is what works when there is no
    # compose file, and what the container image ships.
    sub.add_parser("accounts", help="list accounts on the session server")
    p_inv = sub.add_parser("invite", help="create an invite code")
    p_inv.add_argument("--uses", default="1", help="how many accounts it is good for")
    p_inv.add_argument("--note", default="", help="a reminder of who it was for")
    sub.add_parser("invites", help="outstanding invite codes")
    p_rinv = sub.add_parser("revoke-invite", help="revoke an invite code")
    p_rinv.add_argument("code")
    p_ban = sub.add_parser("ban", help="ban an account and disconnect them")
    p_ban.add_argument("name")
    p_ban.add_argument("reason", nargs="*", help="shown to them, and in the list")
    p_unban = sub.add_parser("unban", help="lift a ban")
    p_unban.add_argument("name")
    p_op = sub.add_parser("operator", help="grant or revoke operator")
    p_op.add_argument("name")
    p_op.add_argument("--off", action="store_true", help="revoke instead of grant")

    args = parser.parse_args()

    if args.cmd == "configure":
        configure(args)
    elif args.cmd == "up":
        warn_if_stale()
        rc = compose("up", "-d", "--build", *services()).returncode
        if rc == 0:
            settings = load_settings()
            where = (
                f"https://{settings['domain']}"
                if settings["mode"] == "proxy" and settings["letsencrypt"]
                else f"http://{settings['domain']}"
                if settings["mode"] == "proxy"
                else f"http://localhost:{settings['port']}"
            )
            print(f"{GREEN}SemiBox is up{RESET} → {where}")
        sys.exit(rc)
    elif args.cmd == "down":
        sys.exit(compose("down").returncode)
    elif args.cmd == "restart":
        sys.exit(compose("restart", "web").returncode)
    elif args.cmd == "status":
        compose("ps")
        sys.exit(0 if check_health() else 1)
    elif args.cmd == "update":
        sys.exit(update(args))
    elif args.cmd == "logs":
        sys.exit(compose("logs", *(["-f"] if args.follow else []), "web").returncode)
    elif args.cmd == "accounts":
        sys.exit(admin("list"))
    elif args.cmd == "invite":
        sys.exit(admin("invite", "--uses", str(args.uses), "--note", args.note))
    elif args.cmd == "invites":
        sys.exit(admin("invites"))
    elif args.cmd == "revoke-invite":
        sys.exit(admin("revoke-invite", args.code))
    elif args.cmd == "ban":
        sys.exit(admin("ban", args.name, *args.reason))
    elif args.cmd == "unban":
        sys.exit(admin("unban", args.name))
    elif args.cmd == "operator":
        sys.exit(admin("operator", args.name, *(["--off"] if args.off else [])))
    elif args.cmd == "version":
        pkg = json.loads((ROOT / "package.json").read_text())
        rev = sh("git", "rev-parse", "--short", "HEAD", capture=True).stdout.strip() or "unknown"
        print(f"semibox {pkg['version']} ({rev})")


if __name__ == "__main__":
    main()
