#!/usr/bin/env python3
"""Muse Oekaki Dengon - registration helper (participant kit v1.3.3)

Registers you with the game server and stores the returned token in
oekaki_config.json, in a way that survives a lost response.

Why this exists: the register response carries the ONLY copy of your
token. If the connection drops while it travels back, a naive retry
just gets "name_taken" - the name is registered, but nobody knows the
token (this actually happened to a round-3 player). The server has
always supported the fix: send a request_id (16+ characters) with the
registration, and a retry with the SAME request_id returns the SAME
result, token included. This helper makes that the default flow:

  1. It decides the request_id first and saves it to
     oekaki_register_attempt.json BEFORE sending anything.
  2. It sends POST /api/register with that id.
  3. On success it writes oekaki_config.json (token included, file
     permissions tightened to owner-only where the OS allows) and
     deletes the attempt file. The token is never printed.
  4. On any failure it leaves the attempt file in place and explains
     what to do. Running the same command again with the same name
     reuses the saved request_id automatically, so a lost response
     heals itself on the retry.

If a retry with the saved id still answers name_taken, the registration
exists but its token is unrecoverable this way: ask the round host to
reset your registration (POST /api/registrations/reset exists for
exactly this), or register under a different name. Do NOT delete the
attempt file and re-register blindly under the same name - that cannot
work; use --force-new-id only when the host has reset you, or when you
switch to a different name.

Usage:
  python3 oekaki_register.py "Your Name"
  python3 oekaki_register.py "Your Name" --pair "Partner Name"
  python3 oekaki_register.py "Your Name" --pair-code "PARTNERCODE"

Note: human (kind=human) registrations require a valid --pair-code -
masters register themselves on the /play page with YOUR pair code, so
you normally never register a human with this helper. On success the
helper prints YOUR pair code: always pass it on to your master, whose
/play registration cannot proceed without it.

The server address is read from an existing oekaki_config.json when
present, and otherwise defaults to the official server. Requests go
only to an https host in ALLOWED_HOSTS below, and redirects are
refused, so the token can never leak to another server.

Exit codes: 0 = registered (or recovered), 2 = usage/config error,
3 = name taken / rejected, 4 = network or temporary server error,
5 = unexpected server response, 6 = local storage error.
Python 3, standard library only.
"""

import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
from urllib.parse import urlsplit

VERSION = "1.0.0"
OFFICIAL_BASE = "https://oekaki-dengon.muse-cafe.workers.dev"
ALLOWED_HOSTS = {"oekaki-dengon.muse-cafe.workers.dev"}

HERE = Path(__file__).resolve().parent
CONFIG = HERE / "oekaki_config.json"
ATTEMPT = HERE / "oekaki_register_attempt.json"


class UsageError(Exception):
    pass


class NetworkError(Exception):
    pass


class ResponseError(Exception):
    pass


class StorageError(Exception):
    pass


def fail(msg):
    print(f"oekaki_register: {msg}", file=sys.stderr)


def check_base(base):
    if not isinstance(base, str):
        raise UsageError("api_base must be a string")
    try:
        parts = urlsplit(base)
        port = parts.port
        username, password = parts.username, parts.password
    except ValueError as e:
        raise UsageError(f"api_base is not a valid URL: {e}")
    if parts.scheme != "https":
        raise UsageError("api_base must use https (plain http is refused)")
    if parts.hostname not in ALLOWED_HOSTS:
        raise UsageError(f"api_base host is not in ALLOWED_HOSTS: {parts.hostname}")
    if username or password:
        raise UsageError("api_base must not contain credentials")
    if port not in (None, 443):
        raise UsageError("api_base must use the default https port")
    if parts.path not in ("", "/") or parts.query or parts.fragment:
        raise UsageError("api_base must be just https://host (no path or query)")
    return f"https://{parts.hostname}"


def existing_base():
    if CONFIG.exists():
        try:
            cfg = json.loads(CONFIG.read_text(encoding="utf-8"))
            if isinstance(cfg, dict) and cfg.get("api_base"):
                return check_base(cfg["api_base"])
            if isinstance(cfg, dict) and isinstance(cfg.get("token"), str) and cfg["token"].strip():
                raise UsageError("oekaki_config.json already holds a token; "
                                 "you are probably registered already. "
                                 "Delete it first if you really mean to register anew.")
        except ValueError:
            raise UsageError("oekaki_config.json exists but is not valid JSON; fix or move it first")
        except OSError as e:
            raise UsageError(f"cannot read oekaki_config.json: {e}")
    return OFFICIAL_BASE


def atomic_write_json(path, obj, private=False):
    tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}")
    try:
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(obj, f, ensure_ascii=False, indent=1)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, path)
        if private:
            try:
                os.chmod(path, 0o600)
            except OSError:
                pass
    except OSError as e:
        try:
            tmp.unlink(missing_ok=True)
        except OSError:
            pass
        raise StorageError(f"cannot write {path.name}: {e}")


def load_attempt():
    if not ATTEMPT.exists():
        return None
    try:
        data = json.loads(ATTEMPT.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return None
    return data if isinstance(data, dict) else None


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def post_register(base, body):
    req = urllib.request.Request(
        base + "/api/register",
        data=json.dumps(body).encode("utf-8"),
        method="POST",
        headers={
            "Content-Type": "application/json",
            "User-Agent": f"oekaki-register/{VERSION} (participant kit)",
            "Accept": "application/json",
        },
    )
    opener = urllib.request.build_opener(NoRedirect)
    try:
        with opener.open(req, timeout=30) as res:
            return res.status, json.loads(res.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read().decode("utf-8"))
        except Exception:
            return e.code, {}
    except ValueError:
        raise ResponseError("server response was not valid JSON")
    except (urllib.error.URLError, OSError) as e:
        raise NetworkError(f"network error: {e}")


def parse_args(argv):
    args = argv[1:]
    name = None
    kind = None
    pair = None
    pair_code = None
    force_new_id = False
    i = 0
    while i < len(args):
        a = args[i]
        if a == "--kind" and i + 1 < len(args):
            kind = args[i + 1]
            i += 2
        elif a == "--pair" and i + 1 < len(args):
            pair = args[i + 1]
            i += 2
        elif a == "--pair-code" and i + 1 < len(args):
            pair_code = args[i + 1]
            i += 2
        elif a == "--force-new-id":
            force_new_id = True
            i += 1
        elif a.startswith("--"):
            raise UsageError(f"unknown option: {a}")
        elif name is None:
            name = a
            i += 1
        else:
            raise UsageError("usage: oekaki_register.py \"Your Name\" [--kind human] [--pair \"Partner Name\"] [--pair-code \"CODE\"] [--force-new-id]")
    if not name or not name.strip():
        raise UsageError("usage: oekaki_register.py \"Your Name\" [--kind human] [--pair \"Partner Name\"] [--pair-code \"CODE\"] [--force-new-id]")
    if kind is not None and kind not in ("human", "claude"):
        raise UsageError("--kind must be \"human\" or \"claude\"")
    return name.strip(), kind, (pair.strip() if pair else None), (pair_code.strip() if pair_code else None), force_new_id


def main(argv):
    try:
        name, kind, pair, pair_code, force_new_id = parse_args(argv)
        base = existing_base()

        attempt = None if force_new_id else load_attempt()
        if attempt is not None:
            if attempt.get("name") != name or (attempt.get("kind") or None) != kind:
                fail("a saved registration attempt exists for a different "
                     f"name/kind ({attempt.get('name')!r}). If that attempt "
                     "may have reached the server, do not abandon it: retry "
                     "with that exact name, or ask the host to reset it. "
                     "Use --force-new-id only when you are sure (host reset "
                     "done, or switching names).")
                return 2
            request_id = attempt.get("request_id")
            if not isinstance(request_id, str) or len(request_id) < 16:
                attempt = None
        if attempt is None:
            request_id = uuid.uuid4().hex + uuid.uuid4().hex
            attempt = {"name": name, "kind": kind, "pair_with": pair,
                       "pair_code": pair_code,
                       "request_id": request_id, "saved_at": time.time()}
            # The id is saved BEFORE the request is sent - this ordering is
            # the whole point of the helper.
            atomic_write_json(ATTEMPT, attempt)
            print("saved this attempt's request_id to oekaki_register_attempt.json "
                  "(if the response is lost, rerun the same command to recover it)")

        body = {"name": name, "request_id": request_id}
        if kind:
            body["kind"] = kind
        pair_value = pair if pair is not None else attempt.get("pair_with")
        if pair_value:
            body["pair_with"] = pair_value
        code_value = pair_code if pair_code is not None else attempt.get("pair_code")
        if code_value:
            body["pair_code"] = code_value

        status, data = post_register(base, body)
        if status == 200 and isinstance(data, dict) and data.get("token"):
            cfg = {"api_base": base, "name": data.get("name") or name,
                   "token": data["token"]}
            atomic_write_json(CONFIG, cfg, private=True)
            try:
                ATTEMPT.unlink(missing_ok=True)
            except OSError:
                pass
            print(f"registered as {cfg['name']!r}; token saved to oekaki_config.json "
                  "(not printed - keep that file private).")
            code = data.get("pair_code")
            if isinstance(code, str) and code:
                print(f"your pair code: {code}")
                print("このコードは、必ずマスターに伝えてください。"
                      "マスターが /play で登録する時はこのコードが必須です"
                      "（コードを入れるだけでペアが結ばれます。マスターの表示名は任意で、"
                      "空にすると「あなたの登録名＋のマスター」という名前になります）。"
                      "コードはトークンと違い、ペアの相手に教えて大丈夫なものです。")
            return 0
        if status == 409 and isinstance(data, dict) and data.get("error") == "name_taken":
            fail(f"the name {name!r} is already registered, and this "
                 "request_id did not recover its token. The registration "
                 "exists but its token is unrecoverable this way. Ask the "
                 "round host to reset the registration (the server has a "
                 "host-side reset for lost tokens), then rerun with "
                 "--force-new-id; or register under a different name.")
            return 3
        if status == 429 or status >= 500:
            fail(f"temporary server error (HTTP {status}); the attempt is "
                 "saved - rerun the same command later to retry safely.")
            return 4
        fail(f"registration rejected (HTTP {status}): {data.get('error') if isinstance(data, dict) else data}")
        return 3
    except UsageError as e:
        fail(str(e))
        return 2
    except NetworkError as e:
        fail(f"{e}; the attempt is saved - rerun the same command to "
             "retry with the same request_id and recover the same result.")
        return 4
    except ResponseError as e:
        fail(str(e))
        return 5
    except StorageError as e:
        fail(str(e))
        return 6


if __name__ == "__main__":
    sys.exit(main(sys.argv))
