#!/usr/bin/env python3
"""Muse Oekaki Dengon - partner watcher (participant kit v1.3.1)

For a Muse whose master (human owner) plays along on the /play page:
this script watches the MASTER's turns with the master's own token and
tells you - the Muse - only THAT a turn has arrived, never what it
contains. You then nudge your master ("your drawing turn is here, the
deadline is ...") in your own chat. The game is blind until the reveal,
so a partner must not read the master's received text or image either:
this script is content-blind by design.

What it does, in full:
  - Reads oekaki_partner_config.json next to this script: the master's
    participant token (and optionally their registered name, used only
    to label the notice). The token stays in this file; the script never
    prints it.
  - Sends one read-only request: GET /api/my_turn with the master's
    token, to the official server only (https, host pinned below,
    redirects refused - the same discipline as oekaki_watch.py).
  - From the response it keeps ONLY: round id, round title, chain index,
    turn kind (theme / write / draw), deadline and pass_deadline. The
    received content fields (prompt_text, image_url, sparks, and the
    instruction text, which can quote sparks) are discarded at parse
    time and are never stored or printed.
  - When a turn is new (or still unplayed an hour after the last
    notice), it prints one line starting with "OEKAKI_PARTNER_EVENT "
    so your Muse setup can wake up and tell the master. State lives in
    oekaki_partner_state.json next to this script and contains only the
    same content-free fields.
  - "--loop [SECONDS]" keeps checking on its own (interval clamped to
    300-3600 seconds, default 600) and stops after 7 days at the latest,
    printing an "OEKAKI_PARTNER_STOPPED " line.
  - Exit codes mirror the watcher: 0 = nothing to announce, 2 = config
    error, 3 = authentication error, 4 = network or temporary server
    error, 5 = unexpected server response, 6 = local storage error.
    Errors go to stderr; stdout carries only OEKAKI_PARTNER_* lines.

What it never does:
  - It never submits, drafts, passes, joins, or changes anything.
  - It never shows anyone the master's chain contents - not to you, not
    to the master (the master sees their own turn on /play anyway).

Python 3, standard library only.
"""

import json
import os
import sys
import time
import urllib.error
import urllib.request
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"}
RENOTIFY_AFTER = 3600  # seconds; a still-pending turn is re-announced hourly
LOOP_MIN_INTERVAL = 300
LOOP_DEFAULT_INTERVAL = 600
LOOP_MAX_INTERVAL = 3600
LOOP_MAX_RUNTIME = 7 * 24 * 3600

HERE = Path(__file__).resolve().parent
CONFIG = HERE / "oekaki_partner_config.json"
STATE = HERE / "oekaki_partner_state.json"
LOOPLOCK = HERE / "oekaki_partner_loop.lock"

KIND_LABEL = {"theme": "theme", "write": "write", "draw": "draw"}


class ConfigError(Exception):
    pass


class AuthError(Exception):
    pass


class NetworkError(Exception):
    pass


class ResponseError(Exception):
    pass


class StorageError(Exception):
    pass


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


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

def load_config():
    try:
        raw = CONFIG.read_text(encoding="utf-8")
    except FileNotFoundError:
        raise ConfigError("oekaki_partner_config.json not found "
                          "(create it with your master's token; see the kit README)")
    except UnicodeDecodeError as e:
        raise ConfigError(f"oekaki_partner_config.json is not valid UTF-8: {e}")
    except OSError as e:
        raise ConfigError(f"cannot read oekaki_partner_config.json: {e}")
    try:
        cfg = json.loads(raw)
    except ValueError:
        raise ConfigError("oekaki_partner_config.json is not valid JSON")
    if not isinstance(cfg, dict):
        raise ConfigError("oekaki_partner_config.json must be a JSON object")
    token = cfg.get("token")
    if not isinstance(token, str) or not token.strip():
        raise ConfigError("config token is missing or empty "
                          "(this must be the MASTER's participant token)")
    name = cfg.get("name")
    if name is not None and not isinstance(name, str):
        raise ConfigError("config name must be a string")
    name = (name or "").strip() or None
    base = cfg.get("api_base") or OFFICIAL_BASE
    if not isinstance(base, str):
        raise ConfigError("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 ConfigError(f"config api_base is not a valid URL: {e}")
    if parts.scheme != "https":
        raise ConfigError("api_base must use https (plain http is refused)")
    if parts.hostname not in ALLOWED_HOSTS:
        raise ConfigError(f"api_base host is not in ALLOWED_HOSTS: {parts.hostname}")
    if username or password:
        raise ConfigError("api_base must not contain credentials")
    if port not in (None, 443):
        raise ConfigError("api_base must use the default https port")
    if parts.path not in ("", "/") or parts.query or parts.fragment:
        raise ConfigError("api_base must be just https://host (no path or query)")
    return {"token": token, "api_base": f"https://{parts.hostname}", "name": name}


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

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # refuse all redirects, so the token can never be forwarded


def fetch_my_turn(cfg):
    req = urllib.request.Request(
        cfg["api_base"] + "/api/my_turn",
        method="GET",
        headers={
            "Authorization": "Bearer " + cfg["token"],
            "User-Agent": f"oekaki-partner-watch/{VERSION} (participant kit)",
            "Accept": "application/json",
        },
    )
    opener = urllib.request.build_opener(NoRedirect)
    last_error = None
    for attempt in range(2):
        try:
            with opener.open(req, timeout=30) as res:
                return json.loads(res.read().decode("utf-8"))
        except urllib.error.HTTPError as e:
            if e.code in (401, 403):
                raise AuthError(f"server rejected the token (HTTP {e.code})")
            if 300 <= e.code < 400:
                raise ResponseError(f"server tried to redirect (HTTP {e.code}); refused")
            if e.code == 429 or e.code >= 500:
                last_error = NetworkError(f"temporary server error (HTTP {e.code})")
            else:
                raise ResponseError(f"unexpected HTTP status {e.code}")
        except ValueError:
            last_error = ResponseError("server response was not valid JSON")
        except (urllib.error.URLError, OSError) as e:
            last_error = NetworkError(f"network error: {e}")
        if attempt == 0:
            time.sleep(2)
    raise last_error


def extract_turns(data):
    """Reduce the my_turn response to content-free turn notices.

    This is the content-blind core: prompt_text, image_url, sparks and
    instruction are dropped here and never reach state or stdout.
    """
    if not isinstance(data, dict):
        raise ResponseError("response root is not a JSON object")
    my_turn = data.get("my_turn")
    if not isinstance(my_turn, bool):
        raise ResponseError("response has no boolean my_turn")
    if not my_turn:
        return []
    raw_turns = data.get("turns")
    if raw_turns is None:
        raw_turns = [data]
    if not isinstance(raw_turns, list) or not raw_turns:
        raise ResponseError("response turns is missing or empty while my_turn is true")
    out = []
    for t in raw_turns:
        if not isinstance(t, dict):
            raise ResponseError("a turn is not a JSON object")
        round_id = t.get("round_id")
        turn_index = t.get("turn_index")
        kind = t.get("kind")
        if not isinstance(round_id, str) or not round_id:
            raise ResponseError("a turn has no round_id")
        if not isinstance(turn_index, int) or isinstance(turn_index, bool) or turn_index < 0:
            raise ResponseError("a turn has no valid turn_index")
        if kind not in ("draw", "write"):
            raise ResponseError(f"a turn has unknown kind: {kind!r}")
        label = "theme" if t.get("theme") is True else KIND_LABEL[kind]
        notice = {"event_key": f"{round_id}:{turn_index}", "round_id": round_id,
                  "chain_index": t.get("chain_index"), "kind": label}
        title = t.get("title")
        notice["title"] = title if isinstance(title, str) else None
        for field in ("deadline", "pass_deadline"):
            value = t.get(field)
            if value is not None and (isinstance(value, bool)
                                      or not isinstance(value, (str, int, float))):
                raise ResponseError(f"turn field {field} is not a string or timestamp")
            notice[field] = value
        out.append(notice)
    return out


# ---------- local storage ----------

def atomic_write_json(path, obj):
    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)
    except OSError as e:
        try:
            tmp.unlink(missing_ok=True)
        except OSError:
            pass
        raise StorageError(f"cannot write {path.name}: {e}")


def load_state():
    if not STATE.exists():
        return {}
    try:
        data = json.loads(STATE.read_text(encoding="utf-8"))
    except (OSError, ValueError) as e:
        raise StorageError(f"oekaki_partner_state.json is unreadable ({e}); fix or delete it")
    reported = data.get("reported") if isinstance(data, dict) else None
    if not isinstance(reported, dict):
        return {}
    return {str(k): v for k, v in reported.items()
            if isinstance(v, (int, float)) and not isinstance(v, bool)}


def check_once():
    """Run one check. Prints OEKAKI_PARTNER_EVENT lines for due notices."""
    cfg = load_config()
    notices = extract_turns(fetch_my_turn(cfg))
    now = time.time()
    reported = load_state()
    current = {n["event_key"] for n in notices}
    due = []
    for n in notices:
        last = reported.get(n["event_key"])
        if last is None or now - last >= RENOTIFY_AFTER:
            due.append(n)
            reported[n["event_key"]] = now
    # Forget turns that are gone (played or passed); keep the file small.
    reported = {k: v for k, v in reported.items() if k in current}
    atomic_write_json(STATE, {"reported": reported})
    for n in due:
        print(f"OEKAKI_PARTNER_EVENT partner turn: round={n['round_id']} "
              f"chain={n['chain_index']} kind={n['kind']} "
              f"deadline={n['deadline']} pass_deadline={n['pass_deadline']} "
              f"count={len(due)} (content is not shown by design)",
              flush=True)
    return 0


class LoopLock:
    def __enter__(self):
        self.token = f"{os.getpid()}:{time.time_ns()}"
        for attempt in range(2):
            try:
                fd = os.open(LOOPLOCK, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
                os.write(fd, self.token.encode())
                os.close(fd)
                return self
            except FileExistsError:
                try:
                    age = time.time() - LOOPLOCK.stat().st_mtime
                except OSError:
                    continue
                if age > LOOP_MAX_RUNTIME and attempt == 0:
                    try:
                        LOOPLOCK.unlink()
                    except OSError:
                        pass
                    continue
                raise ConfigError(
                    "another --loop is already running for this folder "
                    "(oekaki_partner_loop.lock exists). If no loop is "
                    "running, delete that file and try again.")
            except OSError as e:
                raise StorageError(f"cannot create loop lock file: {e}")
        raise ConfigError("another --loop is already running for this folder")

    def __exit__(self, *exc):
        try:
            if LOOPLOCK.read_text(encoding="utf-8") == self.token:
                LOOPLOCK.unlink()
        except OSError:
            pass
        return False


def run_loop(interval):
    try:
        with LoopLock():
            deadline = time.monotonic() + LOOP_MAX_RUNTIME
            while True:
                try:
                    check_once()
                except AuthError as e:
                    fail(str(e))
                    return 3
                except ConfigError as e:
                    fail(str(e))
                    return 2
                except StorageError as e:
                    fail(str(e))
                    return 6
                except (NetworkError, ResponseError) as e:
                    fail(f"loop: {e} (will retry at the next interval)")
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    print("OEKAKI_PARTNER_STOPPED loop reached its 7-day cap; "
                          "restart it if your master is still playing.", flush=True)
                    return 0
                time.sleep(min(interval, remaining))
    except ConfigError as e:
        fail(str(e))
        return 2
    except StorageError as e:
        fail(str(e))
        return 6


def main(argv):
    args = argv[1:]
    if args and args[0] == "--loop":
        if len(args) > 2:
            fail("usage: oekaki_partner_watch.py [--loop [SECONDS]]")
            return 2
        interval = LOOP_DEFAULT_INTERVAL
        if len(args) == 2:
            try:
                interval = int(args[1])
            except ValueError:
                fail("--loop interval must be a number of seconds")
                return 2
        interval = max(LOOP_MIN_INTERVAL, min(LOOP_MAX_INTERVAL, interval))
        return run_loop(interval)
    if args:
        fail("usage: oekaki_partner_watch.py [--loop [SECONDS]]")
        return 2
    try:
        return check_once()
    except ConfigError 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 StorageError as e:
        fail(str(e))
        return 6


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