#!/usr/bin/env python3
"""Muse Oekaki Dengon - two-phase submit helper (participant kit v1.3.1)

An OPTIONAL helper for playing a turn through the server's two-phase
submit (draft -> confirm), instead of the one-shot submit. It exists
because of a real format slip in round 3: an answer written in the
wrong form (a scene sentence in an ogiri round) went straight in.
With two phases you see your own answer and the turn's rule side by
side BEFORE anything is committed, which is exactly when a format
slip is visible.

Flow of the "draft" command:
  1. (draw turns only) the image file is uploaded via POST /api/images.
  2. POST /api/rounds/<id>/draft parks the answer; the chain does NOT
     advance. The server returns the parked content together with the
     turn's instruction.
  3. This script prints both, then asks for confirmation on stdin.
     Only a "y" answer sends POST /api/rounds/<id>/confirm, which
     commits the draft. Anything else leaves the draft parked (it can
     be confirmed, overwritten by a new draft, discarded with the
     "undraft" command, and it disappears on its own if the turn
     passes).

Commands:
  python3 oekaki_submit.py turns
      List your pending turns (round, chain, kind, deadline).
  python3 oekaki_submit.py draft --round <id> --chain <n> --text "..."
  python3 oekaki_submit.py draft --round <id> --chain <n> --image <file>
      Park a draft, show content + rule, ask, and confirm on "y".
      Add --no-confirm to park only (no prompt, no confirm).
  python3 oekaki_submit.py confirm --round <id> --chain <n>
  python3 oekaki_submit.py undraft --round <id> --chain <n>

Reads oekaki_config.json next to this script (your token; see
oekaki_register.py if you have none). The token is sent only to the
official server (https, host pinned below, redirects refused) and is
never printed. Unlike the watcher, this helper WRITES to the server -
that is its job - so it is a separate file you run deliberately, once
per turn you play through it.

Exit codes: 0 = done, 2 = usage/config error, 3 = authentication or
not-your-turn error, 4 = network or temporary server error,
5 = unexpected server response, 6 = local file error.
Python 3, standard library only.
"""

import json
import mimetypes
import os
import sys
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"


class UsageError(Exception):
    pass


class AuthError(Exception):
    pass


class NetworkError(Exception):
    pass


class ResponseError(Exception):
    pass


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


# ---------- config ----------

def load_config():
    try:
        raw = CONFIG.read_text(encoding="utf-8")
    except FileNotFoundError:
        raise UsageError("oekaki_config.json not found (register first - see oekaki_register.py)")
    except UnicodeDecodeError as e:
        raise UsageError(f"oekaki_config.json is not valid UTF-8: {e}")
    except OSError as e:
        raise UsageError(f"cannot read oekaki_config.json: {e}")
    try:
        cfg = json.loads(raw)
    except ValueError:
        raise UsageError("oekaki_config.json is not valid JSON")
    if not isinstance(cfg, dict):
        raise UsageError("oekaki_config.json must be a JSON object")
    token = cfg.get("token")
    if not isinstance(token, str) or not token.strip():
        raise UsageError("config token is missing or empty")
    base = cfg.get("api_base") or OFFICIAL_BASE
    if not isinstance(base, str):
        raise UsageError("config 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"config 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 {"token": token, "api_base": f"https://{parts.hostname}"}


# ---------- network ----------

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


def request_json(cfg, method, path, body=None):
    data = json.dumps(body).encode("utf-8") if body is not None else None
    headers = {
        "Authorization": "Bearer " + cfg["token"],
        "User-Agent": f"oekaki-submit/{VERSION} (participant kit)",
        "Accept": "application/json",
    }
    if data is not None:
        headers["Content-Type"] = "application/json"
    req = urllib.request.Request(cfg["api_base"] + path, data=data,
                                 method=method, headers=headers)
    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:
        if e.code in (401, 403):
            try:
                detail = json.loads(e.read().decode("utf-8"))
            except Exception:
                detail = {}
            raise AuthError(f"server refused (HTTP {e.code}): {detail.get('error') or 'auth or not your turn'}")
        if 300 <= e.code < 400:
            raise ResponseError(f"server tried to redirect (HTTP {e.code}); refused")
        try:
            detail = json.loads(e.read().decode("utf-8"))
        except Exception:
            detail = {}
        if e.code == 429 or e.code >= 500:
            raise NetworkError(f"temporary server error (HTTP {e.code}): {detail.get('error') or ''}")
        raise ResponseError(f"server error (HTTP {e.code}): {detail.get('error') or 'unknown'}")
    except ValueError:
        raise ResponseError("server response was not valid JSON")
    except (urllib.error.URLError, OSError) as e:
        raise NetworkError(f"network error: {e}")


def upload_image(cfg, path):
    p = Path(path)
    try:
        data = p.read_bytes()
    except OSError as e:
        raise UsageError(f"cannot read image file: {e}")
    if len(data) > 1024 * 1024:
        raise UsageError("image is over the 1MB server cap")
    ctype = mimetypes.guess_type(p.name)[0] or "image/png"
    if ctype not in ("image/png", "image/jpeg", "image/webp", "image/gif"):
        raise UsageError(f"unsupported image type: {ctype} (png/jpeg/webp/gif only)")
    req = urllib.request.Request(
        cfg["api_base"] + "/api/images", data=data, method="POST",
        headers={
            "Authorization": "Bearer " + cfg["token"],
            "Content-Type": ctype,
            "User-Agent": f"oekaki-submit/{VERSION} (participant kit)",
            "Accept": "application/json",
            "X-Request-Id": uuid.uuid4().hex + uuid.uuid4().hex,
        })
    opener = urllib.request.build_opener(NoRedirect)
    try:
        with opener.open(req, timeout=60) as res:
            out = json.loads(res.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        try:
            detail = json.loads(e.read().decode("utf-8"))
        except Exception:
            detail = {}
        raise ResponseError(f"upload failed (HTTP {e.code}): {detail.get('error') or 'unknown'}")
    except ValueError:
        raise ResponseError("upload response was not valid JSON")
    except (urllib.error.URLError, OSError) as e:
        raise NetworkError(f"network error: {e}")
    url = out.get("url") if isinstance(out, dict) else None
    if not url:
        raise ResponseError("upload response has no url")
    return url


def new_rid():
    return uuid.uuid4().hex + uuid.uuid4().hex


# ---------- commands ----------

def cmd_turns(cfg):
    status, data = request_json(cfg, "GET", "/api/my_turn")
    turns = data.get("turns") if isinstance(data, dict) else None
    if not turns:
        print("no pending turns.")
        return 0
    for t in turns:
        kind = "theme" if t.get("theme") else t.get("kind")
        print(f"round={t.get('round_id')} chain={t.get('chain_index')} "
              f"kind={kind} style={t.get('style') or 'classic'} "
              f"turn_index={t.get('turn_index')} "
              f"deadline={t.get('deadline')} pass_deadline={t.get('pass_deadline')}"
              + (" [draft parked]" if t.get("draft") else ""))
    return 0


def find_turn(cfg, round_id, chain_index):
    status, data = request_json(cfg, "GET", "/api/my_turn")
    turns = data.get("turns") if isinstance(data, dict) else None
    for t in turns or []:
        if t.get("round_id") == round_id and t.get("chain_index") == chain_index:
            return t
    raise AuthError("that turn is not among your pending turns "
                    "(already played, passed, or not yours)")


def cmd_draft(cfg, round_id, chain_index, text, image, no_confirm):
    turn = find_turn(cfg, round_id, chain_index)
    body = {"chain_index": chain_index,
            "expected_turn_index": turn.get("turn_index"),
            "request_id": new_rid()}
    if image:
        body["image_url"] = upload_image(cfg, image)
        print(f"uploaded: {body['image_url']}")
    else:
        body["text"] = text
    status, data = request_json(cfg, "POST", f"/api/rounds/{round_id}/draft", body)
    if not isinstance(data, dict) or not data.get("drafted"):
        raise ResponseError(f"unexpected draft response: {data}")
    print("--- draft parked (the chain has NOT advanced) ---")
    draft = data.get("draft") or {}
    if draft.get("text") is not None:
        print(f"content (text): {draft['text']}")
    if draft.get("image_url") is not None:
        print(f"content (image): {cfg['api_base']}{draft['image_url']}")
    print(f"rule for this turn: {data.get('instruction')}")
    print("--------------------------------------------------")
    if no_confirm:
        print("parked only (--no-confirm). Submit later with: "
              f"oekaki_submit.py confirm --round {round_id} --chain {chain_index}")
        return 0
    try:
        answer = input("この内容で提出しますか？ [y/N] ").strip().lower()
    except EOFError:
        answer = ""
    if answer not in ("y", "yes"):
        print("left as a draft. Confirm later, overwrite with a new draft, "
              "or discard it with the undraft command.")
        return 0
    return cmd_confirm(cfg, round_id, chain_index)


def cmd_confirm(cfg, round_id, chain_index):
    status, data = request_json(cfg, "POST", f"/api/rounds/{round_id}/confirm",
                                {"chain_index": chain_index, "request_id": new_rid()})
    if not isinstance(data, dict) or not data.get("confirmed"):
        raise ResponseError(f"unexpected confirm response: {data}")
    print(f"submitted: round={round_id} chain={chain_index} is now at "
          f"{data.get('round', {}).get('turn_index')}/{data.get('round', {}).get('turn_count')} steps.")
    return 0


def cmd_undraft(cfg, round_id, chain_index):
    status, data = request_json(cfg, "POST", f"/api/rounds/{round_id}/undraft",
                                {"chain_index": chain_index, "request_id": new_rid()})
    print(f"draft discarded (had_draft={data.get('had_draft') if isinstance(data, dict) else '?'}).")
    return 0


def parse_opts(args, allowed):
    opts = {}
    i = 0
    while i < len(args):
        a = args[i]
        if a in allowed and i + 1 < len(args):
            opts[a] = args[i + 1]
            i += 2
        elif a == "--no-confirm":
            opts[a] = True
            i += 1
        else:
            raise UsageError(f"unknown or incomplete option: {a}")
    return opts


def need(opts, key):
    value = opts.get(key)
    if value is None:
        raise UsageError(f"missing required option {key}")
    return value


def main(argv):
    args = argv[1:]
    if not args:
        fail("usage: oekaki_submit.py turns | draft --round <id> --chain <n> "
             "(--text \"...\" | --image <file>) [--no-confirm] | "
             "confirm --round <id> --chain <n> | undraft --round <id> --chain <n>")
        return 2
    cmd = args[0]
    try:
        cfg = load_config()
        if cmd == "turns":
            if len(args) != 1:
                raise UsageError("turns takes no options")
            return cmd_turns(cfg)
        if cmd == "draft":
            opts = parse_opts(args[1:], ("--round", "--chain", "--text", "--image"))
            round_id = need(opts, "--round")
            chain_index = int(need(opts, "--chain"))
            text = opts.get("--text")
            image = opts.get("--image")
            if (text is None) == (image is None):
                raise UsageError("draft needs exactly one of --text or --image")
            return cmd_draft(cfg, round_id, chain_index, text, image,
                             bool(opts.get("--no-confirm")))
        if cmd in ("confirm", "undraft"):
            opts = parse_opts(args[1:], ("--round", "--chain"))
            round_id = need(opts, "--round")
            chain_index = int(need(opts, "--chain"))
            return (cmd_confirm if cmd == "confirm" else cmd_undraft)(cfg, round_id, chain_index)
        raise UsageError(f"unknown command: {cmd}")
    except UsageError as e:
        fail(str(e))
        return 2
    except AuthError as e:
        fail(str(e))
        return 3
    except NetworkError as e:
        fail(str(e))
        return 4
    except ResponseError as e:
        fail(str(e))
        return 5
    except ValueError as e:
        fail(f"bad numeric option: {e}")
        return 2


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