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

What this script does, in full:
  - Reads oekaki_config.json next to this script (your own participant token;
    the server address may be omitted and defaults to the official server).
  - Sends read-only requests: GET /api/my_turn with your token, and - when
    the config also carries your registered "name" - GET /api/rounds, to
    tell whether you are still in an open or running round.
  - Keeps unprocessed turns in oekaki_pending.json (a queue, not a snapshot).
    When a new turn appears, or an unprocessed turn has not been announced
    for over an hour, it prints one line starting with "OEKAKI_EVENT " so
    your Muse (or hook setup) can wake up and play.
  - Pending events carry the turn's style (classic/ogiri) and the server's
    instruction line for that turn, so the woken Muse can check its
    answer's form against the server's own guidance before submitting.
  - After playing a turn, your Muse runs this script once with
    "--ack ROUND_ID:TURN_INDEX" to remove that event from the queue.
    That is a local file operation only; it sends nothing anywhere.
  - Participation-scoped lifetime: when the config carries your registered
    name and you are in no open or running round, it prints a line
    starting with "OEKAKI_INACTIVE ". That is the signal to stop the
    watcher until you join a round again - the watcher is meant to run
    only while you are playing. The decision is conservative: the name is
    first checked against the server's own record of who the token
    belongs to (a mismatch disables auto-stop and warns instead), a
    malformed rounds response counts as "unknown" (never as "not
    playing"), and "not playing" must be confirmed on two consecutive
    checks before the signal fires. After the first signal it re-fires at
    most once a day while you remain inactive, in case the first one was
    lost.
  - "--loop [SECONDS]" keeps checking on its own: the interval is clamped
    to 300-3600 seconds (default 600), the loop ends by itself when
    OEKAKI_INACTIVE fires, and it stops after 7 days at the latest
    (printing an "OEKAKI_STOPPED " line) so it can never run away forever.
  - Exit codes: 0 = nothing to announce (or another run is in progress),
    2 = config error, 3 = authentication error (401/403), 4 = network or
    temporary server error, 5 = unexpected server response (including
    redirects), 6 = local storage error. Errors are printed to stderr;
    stdout is used only for OEKAKI_EVENT / OEKAKI_ACK / OEKAKI_INACTIVE /
    OEKAKI_STOPPED lines.

What it never does:
  - It never submits, uploads, joins, or changes anything on the server
    (both GETs are read-only).
  - It never sends your token anywhere except as the Authorization header
    to the official game server. The destination is pinned: the config must
    be HTTPS and the host must be in ALLOWED_HOSTS below, and redirects are
    refused, so a config typo cannot leak the token to another server.
    (If you run your own compatible server, edit that one visible line.)
  - It reads no local files other than its own config / state / pending /
    lock files in this script's folder.

Run it on any interval you like (10 minutes is a good default) from a hook,
cron, or scheduler in your own environment, or start it once with --loop.
Either way, start it when you join a round; it tells you when it can stop.
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.3.2"
OFFICIAL_BASE = "https://oekaki-dengon.muse-cafe.workers.dev"
ALLOWED_HOSTS = {"oekaki-dengon.muse-cafe.workers.dev"}
MAX_REPORTED = 200
RENOTIFY_AFTER = 3600  # seconds; unprocessed turns are re-announced hourly
LOCK_STALE_AFTER = 600  # seconds; a lock older than this is treated as stale
LOOP_MIN_INTERVAL = 300  # seconds; --loop never polls faster than this
LOOP_DEFAULT_INTERVAL = 600
LOOP_MAX_INTERVAL = 3600
LOOP_MAX_RUNTIME = 7 * 24 * 3600  # seconds; --loop stops itself after 7 days
INACTIVE_CONFIRM_STREAK = 2  # consecutive "not playing" results before the signal
INACTIVE_RENOTIFY_AFTER = 24 * 3600  # seconds; the signal re-fires at most daily

HERE = Path(__file__).resolve().parent
CONFIG = HERE / "oekaki_config.json"
STATE = HERE / "oekaki_state.json"
PENDING = HERE / "oekaki_pending.json"
LOCK = HERE / "oekaki_watch.lock"
LOOPLOCK = HERE / "oekaki_loop.lock"


class ConfigError(Exception):
    pass


class AuthError(Exception):
    pass


class NetworkError(Exception):
    pass


class ResponseError(Exception):
    pass


class StorageError(Exception):
    pass


class LockBusy(Exception):
    pass


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


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

def load_config():
    try:
        raw = CONFIG.read_text(encoding="utf-8")
    except FileNotFoundError:
        raise ConfigError("oekaki_config.json not found (see config.example.json)")
    except UnicodeDecodeError as e:
        raise ConfigError(f"oekaki_config.json is not valid UTF-8: {e}")
    except OSError as e:
        raise ConfigError(f"cannot read oekaki_config.json: {e}")
    try:
        cfg = json.loads(raw)
    except ValueError:
        raise ConfigError("oekaki_config.json is not valid JSON")
    if not isinstance(cfg, dict):
        raise ConfigError("oekaki_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")
    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_json(cfg, path):
    req = urllib.request.Request(
        cfg["api_base"] + path,
        method="GET",
        headers={
            "Authorization": "Bearer " + cfg["token"],
            "User-Agent": f"oekaki-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 fetch_my_turn(cfg):
    return fetch_json(cfg, "/api/my_turn")


def fetch_rounds(cfg):
    return fetch_json(cfg, "/api/rounds")


def compute_active(rounds_data, name):
    """True when a round in state open/running lists name as a player.

    Returns None when anything about the response is malformed, so the
    caller can treat "unknown" as "stay quiet" and never stop the watcher
    on a guess: a False answer is only given for a fully well-formed list
    in which no open/running round includes the player.
    """
    if not isinstance(rounds_data, dict):
        return None
    rounds = rounds_data.get("rounds")
    if not isinstance(rounds, list):
        return None
    me = name.lower()
    for r in rounds:
        if not isinstance(r, dict):
            return None
        state = r.get("state")
        if not isinstance(state, str):
            return None
        if state not in ("open", "running"):
            continue
        players = r.get("players")
        if not isinstance(players, list) or not all(
                isinstance(p, str) for p in players):
            return None
        if any(p.lower() == me for p in players):
            return True
    return False


def extract_player_name(my_turn_data):
    """The server's own record of the token owner's registered name."""
    if isinstance(my_turn_data, dict):
        value = my_turn_data.get("player_name")
        if isinstance(value, str) and value:
            return value
    return None


def validate_turns(data):
    """Return a normalized list of current turns, or raise ResponseError."""
    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 isinstance(raw_turns, list) and not raw_turns:
        raise ResponseError("response says my_turn is true but lists no turns")
    if not isinstance(raw_turns, list):
        raise ResponseError("response turns is not a list")
    turns = []
    seen = set()
    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}")
        event = {"event_key": f"{round_id}:{turn_index}", "round_id": round_id,
                 "turn_index": turn_index, "kind": kind}
        for field in ("title", "prompt_text", "image_url"):
            value = t.get(field)
            if value is not None and not isinstance(value, str):
                raise ResponseError(f"turn field {field} is not a string")
            event[field] = value
        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")
            event[field] = value
        sparks = t.get("sparks")
        if sparks is not None:
            if not isinstance(sparks, list) or not all(isinstance(s, str) for s in sparks):
                raise ResponseError("turn field sparks is not a list of strings")
            event["sparks"] = sparks
        # style + instruction ride along since watcher 1.3.2 (kit v1.3.1), so
        # the woken Muse knows the round's form (classic vs ogiri) and the
        # server's own guidance for this turn without an extra fetch - the
        # server text is the source of truth for how a turn must be played.
        for field in ("style", "instruction"):
            value = t.get(field)
            if value is not None and not isinstance(value, str):
                raise ResponseError(f"turn field {field} is not a string")
            event[field] = value
        if event["event_key"] not in seen:
            seen.add(event["event_key"])
            turns.append(event)
    return turns


# ---------- 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 _empty_inactive():
    return {"notified": False, "streak": 0, "announced_at": None}


def load_state():
    """Return ({event_key: last_seen_epoch}, inactive_meta).

    inactive_meta is {"notified": bool, "streak": int,
    "announced_at": epoch|None}. Accepts the v1.0 list format for
    "reported" and the v1.2 state shape (a bare inactive_notified flag);
    missing pieces default safely. A structurally unexpected file is
    reported on stderr and treated as empty rather than silently reset.
    """
    if not STATE.exists():
        return {}, _empty_inactive()
    try:
        data = json.loads(STATE.read_text(encoding="utf-8"))
    except (OSError, ValueError) as e:
        raise StorageError(f"oekaki_state.json is unreadable ({e}); fix or delete it")
    if not isinstance(data, dict):
        fail("oekaki_state.json has an unexpected shape; starting with empty state")
        return {}, _empty_inactive()
    inactive = _empty_inactive()
    if data.get("inactive_notified") is True:  # v1.2 shape
        inactive["notified"] = True
    meta = data.get("inactive")
    if isinstance(meta, dict):
        if meta.get("notified") is True:
            inactive["notified"] = True
        streak = meta.get("streak")
        if isinstance(streak, int) and not isinstance(streak, bool) and streak >= 0:
            inactive["streak"] = streak
        announced = meta.get("announced_at")
        if isinstance(announced, (int, float)) and not isinstance(announced, bool):
            inactive["announced_at"] = announced
    reported = data.get("reported")
    if isinstance(reported, list):  # v1.0 format
        return {str(k): 0 for k in reported}, inactive
    if isinstance(reported, dict):
        out = {}
        for k, v in reported.items():
            out[str(k)] = v if isinstance(v, (int, float)) else 0
        return out, inactive
    if reported is not None:
        fail("oekaki_state.json: 'reported' has an unexpected shape; starting fresh")
    return {}, inactive


def load_pending():
    if not PENDING.exists():
        return []
    try:
        data = json.loads(PENDING.read_text(encoding="utf-8"))
    except (OSError, ValueError) as e:
        raise StorageError(f"oekaki_pending.json is unreadable ({e}); fix or delete it")
    events = data.get("events") if isinstance(data, dict) else None
    if not isinstance(events, list):
        raise StorageError("oekaki_pending.json has no events list; fix or delete it")
    out = []
    for ev in events:
        if not isinstance(ev, dict):
            continue
        key = ev.get("event_key")
        if not key and ev.get("round_id") is not None and ev.get("turn_index") is not None:
            key = f"{ev['round_id']}:{ev['turn_index']}"  # v1.0 event without a key
        if not key:
            continue
        ev = dict(ev)
        ev["event_key"] = key
        if not isinstance(ev.get("first_seen_at"), (int, float)):
            ev["first_seen_at"] = 0
        if not isinstance(ev.get("last_notified_at"), (int, float)):
            ev["last_notified_at"] = None
        out.append(ev)
    return out


class FileLock:
    def __enter__(self):
        self.token = f"{os.getpid()}:{time.time_ns()}"
        for attempt in range(2):
            try:
                fd = os.open(LOCK, 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() - LOCK.stat().st_mtime
                except OSError:
                    continue
                if age > LOCK_STALE_AFTER and attempt == 0:
                    try:
                        LOCK.unlink()
                    except OSError:
                        pass
                    continue
                raise LockBusy()
            except OSError as e:
                raise StorageError(f"cannot create lock file: {e}")
        raise LockBusy()

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


# ---------- main flows ----------

def check_once():
    """Run one check. Returns (status, announced_inactive).

    status is "event", "quiet", "inactive" or "busy". announced_inactive
    tells whether this check printed the OEKAKI_INACTIVE line.
    """
    try:
        with FileLock():
            cfg = load_config()
            my_turn_data = fetch_my_turn(cfg)
            turns = validate_turns(my_turn_data)
            active = None
            if cfg["name"]:
                server_name = extract_player_name(my_turn_data)
                if server_name is not None and server_name.lower() != cfg["name"].lower():
                    fail(f"config name {cfg['name']!r} does not match the token's "
                         f"registered name {server_name!r}; participation "
                         "auto-stop is disabled until the config name is fixed")
                else:
                    try:
                        active = compute_active(fetch_rounds(cfg), cfg["name"])
                    except (NetworkError, ResponseError) as e:
                        fail(f"could not check your rounds ({e}); "
                             "treating participation as unknown this time")
                        active = None  # cannot tell this time; stay quiet
            if turns:
                active = True
            now = time.time()
            current_keys = [t["event_key"] for t in turns]
            current_set = set(current_keys)

            reported, inactive = load_state()
            for key in current_set:
                if key in reported:
                    reported[key] = now

            pending = [ev for ev in load_pending() if ev["event_key"] in current_set]
            pending_keys = {ev["event_key"] for ev in pending}
            for t in turns:
                key = t["event_key"]
                if key not in reported and key not in pending_keys:
                    ev = dict(t)
                    ev["first_seen_at"] = now
                    ev["last_notified_at"] = None
                    pending.append(ev)
                    pending_keys.add(key)
                    reported[key] = now

            if len(reported) > MAX_REPORTED:
                others = sorted((k for k in reported if k not in current_set),
                                key=lambda k: reported[k], reverse=True)
                keep = set(current_set) | set(others[:max(0, MAX_REPORTED - len(current_set))])
                reported = {k: v for k, v in reported.items() if k in keep}

            to_notify = [ev for ev in pending
                         if ev["last_notified_at"] is None
                         or now - ev["last_notified_at"] >= RENOTIFY_AFTER]
            for ev in to_notify:
                ev["last_notified_at"] = now

            announce_inactive = False
            if active is True:
                inactive = _empty_inactive()
                status = "event" if to_notify else "quiet"
            elif active is False and not turns:
                inactive["streak"] += 1
                if inactive["streak"] >= INACTIVE_CONFIRM_STREAK:
                    status = "inactive"
                    last = inactive["announced_at"]
                    if not inactive["notified"]:
                        inactive["notified"] = True
                        inactive["announced_at"] = now
                        announce_inactive = True
                    elif last is None or now - last >= INACTIVE_RENOTIFY_AFTER:
                        inactive["announced_at"] = now
                        announce_inactive = True
                else:
                    status = "event" if to_notify else "quiet"
            else:
                inactive["streak"] = 0
                status = "event" if to_notify else "quiet"

            # Save the queue first, then the dedupe state: if the state save
            # fails, the queue still holds the event and nothing is lost.
            atomic_write_json(PENDING, {"events": pending})
            atomic_write_json(STATE, {"reported": reported, "inactive": inactive})

            if to_notify:
                first = to_notify[0]
                print(f"OEKAKI_EVENT your turn: round={first['round_id']} "
                      f"kind={first['kind']} count={len(to_notify)} "
                      f"(details in oekaki_pending.json)", flush=True)
            if announce_inactive:
                print("OEKAKI_INACTIVE no open or running round includes you; "
                      "this watcher can be stopped until you join a round again.",
                      flush=True)
            return status, announce_inactive
    except LockBusy:
        return "busy", False


def run():
    check_once()
    return 0


class LoopLock:
    """One --loop per kit folder. Held for the loop's whole lifetime.

    A lock older than the maximum loop runtime cannot belong to a live
    loop (a loop stops itself by then), so it is treated as stale.
    """

    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 kit folder "
                    "(oekaki_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 kit 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:
        cfg = load_config()
    except ConfigError as e:
        fail(str(e))
        return 2
    if not cfg["name"]:
        fail("config has no name; participation auto-stop is disabled, "
             "so this loop will only stop at its 7-day cap")
    try:
        with LoopLock():
            deadline = time.monotonic() + LOOP_MAX_RUNTIME
            while True:
                try:
                    status, announced = 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)")
                    status, announced = "error", False
                if status == "inactive":
                    if not announced:
                        print("OEKAKI_INACTIVE no open or running round "
                              "includes you; loop stopped.", flush=True)
                    return 0
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    print("OEKAKI_STOPPED loop reached its 7-day cap; "
                          "restart it if you are 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 ack(event_key):
    try:
        with FileLock():
            pending = load_pending()
            rest = [ev for ev in pending if ev["event_key"] != event_key]
            if len(rest) == len(pending):
                fail(f"ack: no pending event with key {event_key}")
                return 6
            atomic_write_json(PENDING, {"events": rest})
            print(f"OEKAKI_ACK {event_key}", flush=True)
            return 0
    except LockBusy:
        fail("ack: another run is in progress; try again in a moment")
        return 6


def main(argv):
    args = argv[1:]
    if len(args) == 2 and args[0] == "--ack":
        try:
            return ack(args[1])
        except StorageError as e:
            fail(str(e))
            return 6
    if args and args[0] == "--loop":
        if len(args) > 2:
            fail("usage: oekaki_watch.py [--ack ROUND_ID:TURN_INDEX] [--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_watch.py [--ack ROUND_ID:TURN_INDEX] [--loop [SECONDS]]")
        return 2
    try:
        return run()
    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))
