File size: 23,757 Bytes
12c9315
8fadc05
12c9315
8fadc05
 
 
12c9315
 
 
8fadc05
12c9315
 
8fadc05
 
 
 
 
12c9315
 
 
 
 
 
 
 
8fadc05
12c9315
 
 
8fadc05
12c9315
 
 
 
 
8fadc05
12c9315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fadc05
 
 
 
 
12c9315
 
 
 
8fadc05
12c9315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fadc05
 
12c9315
8fadc05
 
12c9315
8fadc05
 
 
 
 
 
 
 
 
 
12c9315
8fadc05
 
 
 
 
 
 
 
12c9315
 
 
 
8fadc05
12c9315
 
8fadc05
12c9315
8fadc05
 
 
 
 
12c9315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fadc05
12c9315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fadc05
12c9315
 
 
 
 
 
8fadc05
12c9315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fadc05
12c9315
 
8fadc05
 
 
 
 
 
12c9315
 
 
 
 
 
8fadc05
 
12c9315
8fadc05
 
 
 
 
12c9315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fadc05
12c9315
 
 
 
 
 
 
 
 
8fadc05
12c9315
 
8fadc05
12c9315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fadc05
12c9315
 
 
 
8fadc05
 
12c9315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fadc05
12c9315
 
 
 
8fadc05
12c9315
8fadc05
 
 
 
 
12c9315
 
 
 
 
 
 
 
 
8fadc05
12c9315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fadc05
 
 
 
 
12c9315
8fadc05
12c9315
8fadc05
12c9315
8fadc05
 
 
 
12c9315
 
 
 
 
 
 
 
 
8fadc05
 
 
 
12c9315
8fadc05
 
 
12c9315
8fadc05
12c9315
 
 
 
8fadc05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12c9315
 
 
 
 
 
 
8fadc05
 
12c9315
 
 
 
 
 
8fadc05
 
12c9315
8fadc05
12c9315
8fadc05
 
 
12c9315
 
 
 
 
 
 
 
 
8fadc05
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
"""
play.py - Jogue Ankh contra as IAs no navegador.

    python play.py --models ~/ankh_runs/run1/checkpoints/round_0040.zip
    python play.py                       # sem --models: as IAs jogam aleatoriamente
    python play.py --lan                 # tambem aceita outros aparelhos da mesma rede (1 a 5 humanos)

Abre http://127.0.0.1:8765 . As regras sao as MESMAS do treino (ankh_game.py): este arquivo so
expoe o estado em JSON, aceita a sua jogada e deixa as IAs jogarem os outros assentos.
Precisa de play.html na mesma pasta. So os modelos exigem torch + sb3-contrib; o resto usa a
biblioteca padrao + numpy.

De 1 a 5 jogadores humanos: na janela "Nova partida" cada assento e Humano ou IA (5 humanos = sem IA).
"Mesma tela" revezam no mesmo navegador; "Rede local" (precisa de --lan) cada pessoa abre o link no seu aparelho.
As IAs nao mudam: cada uma decide pela propria perspectiva e a observacao ja traz o numero de jogadores.

Cada jogada vira um QUADRO (frame) com o estado depois dela; a pagina os reproduz um a um.

Informacao secreta: as cartas escolhidas e os lances do Plague de outros jogadores NAO sao enviados
ao navegador (so as cartas ja reveladas e as ja usadas, que sao publicas no jogo).
"""
import argparse
import json
import os
import random
import socket
import threading
import time
import webbrowser
from urllib.parse import parse_qs, urlparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import numpy as np

from ankh_game import (ACTION_END, ACTION_START, AnkhGame, CARD_BONUS, CARD_NAMES, EVENTS, GODS,
                       KIND_NAMES, MON_TYPES, N_CHOICE, POWER_NAMES, RED_SPACES, TOP,
                       ANUBIS_SLOTS, Phase)
from ankh_map import SCENARIOS, build_board
from ankh_obs import Encoder
import replay
from replay import describe

replay.ACTIONS[3] = "Desbloquear poder Ankh"       # o rotulo antigo do replay.py diz 'sem efeito'

HERE = os.path.dirname(os.path.abspath(__file__))
SECRET_PHASES = (Phase.BATTLE_CARD, Phase.BID)        # escolhas ocultas ate serem reveladas
# escolhas so de selecao (sem efeito visivel): nao geram quadro; o destino mostra a jogada inteira
SELECT_ONLY = (Phase.MOVE_SELECT, Phase.SUMMON_TYPE, Phase.ATTUNE_SRC, Phase.UNDERWORLD_SRC)
EVENT_TEXT = {"ctrl": "Controlar Monumento", "camel": "Caravana de Camelos", "conf": "CONFLITO"}


def seat_label(g, p):
    return f"J{p} ({GODS[g.god[p]]})"


class Session:
    def __init__(self, models, device, deterministic):
        self.lock = threading.RLock()
        self.board = build_board()
        self.models = [os.path.expanduser(m) for m in models]
        self.device = device
        self.deterministic = deterministic
        self._policies = {}
        self.g = None
        self.humans = [0]
        self.mode = "hot"
        self.lan = False
        self.urls = []
        self.game_id = 0
        self.ai_kind = "random"
        self.log = []
        self.camel_new = None
        self.warnings = []
        self.events = []

    # ---------------- IA ----------------
    def policy(self, idx):
        if idx in self._policies:
            return self._policies[idx]
        try:
            from sb3_contrib import MaskablePPO
            m = MaskablePPO.load(self.models[idx], device=self.device)
            det = self.deterministic

            def act(obs, mask):
                a, _ = m.predict(obs, action_masks=mask, deterministic=det)
                return int(a)
        except Exception as e:                                     # noqa: BLE001
            self.warnings.append(f"modelo {self.models[idx]} nao carregou ({e}); IA aleatoria")
            print("AVISO:", self.warnings[-1])
            act = None
        self._policies[idx] = act
        return act

    def ai_action(self, dec):
        mask = dec.mask
        fn = None
        if self.ai_kind != "random":
            fn = self.policy(int(self.ai_kind))
        if fn is None:
            return int(random.choice(np.flatnonzero(mask)))
        a = fn(self.enc.encode(dec), mask)
        return a if mask[a] else int(random.choice(np.flatnonzero(mask)))

    # ---------------- jogo ----------------
    def new_game(self, scenario, seats, ai, seed, mode="hot"):
        """seats: lista com um item por assento: {"type": "human"|"ai", "god": -1 ou id do deus}."""
        with self.lock:
            if scenario not in SCENARIOS:
                raise ValueError("cenario desconhecido")
            P = SCENARIOS[scenario]["n_players"]
            seats = list(seats or [{"type": "human"}])
            seats = (seats + [{"type": "ai", "god": -1}] * P)[:P]
            humans = [s for s in range(P) if seats[s].get("type") == "human"]
            if not humans:
                raise ValueError("escolha pelo menos 1 jogador humano")
            if mode not in ("hot", "lan"):
                mode = "hot"
            if mode == "lan" and not self.lan:
                raise ValueError("para jogar em rede local inicie o servidor com --lan")
            seed = int(seed) if seed not in (None, "") else int(time.time()) % 10**6
            gods = [None] * P
            for s in range(P):
                gd = seats[s].get("god", -1)
                if gd not in (None, "", -1) and int(gd) >= 0:
                    gods[s] = int(gd)
            chosen = [x for x in gods if x is not None]
            if len(chosen) != len(set(chosen)):
                raise ValueError("dois assentos escolheram o mesmo deus")
            rng = np.random.default_rng(seed + 1)
            for s in range(P):
                if gods[s] is None:
                    free = [x for x in range(len(GODS)) if x not in gods]
                    gods[s] = int(rng.choice(free))
            self.g = AnkhGame(scenario, seed=seed, board=self.board)
            self.g.reset(seed=seed, gods=gods, scenario=scenario)
            self.enc = Encoder(self.g)
            self.humans, self.mode = humans, mode
            self.ai_kind = "random" if ai in (None, "", "random") else str(int(ai))
            self.log, self.camel_new, self.seed = [], None, seed
            self.events, self.game_id = [], self.game_id + 1
            hum = ", ".join(seat_label(self.g, s) for s in humans)
            ais = ", ".join(seat_label(self.g, s) for s in range(P) if s not in humans) or "nenhuma"
            self.say(f"Nova partida: {scenario} ({P} jogadores), seed {seed}. Humanos: {hum}. IAs: {ais}.")
            self._run_ai()

    def say(self, text):
        self.log.append(text)
        del self.log[:-400]

    def _before(self, dec):
        g = self.g
        if dec.phase == Phase.CAMEL_KEEP:
            self.camel_new = sorted((r for r in g.regions if r not in g.tokens), key=min)

    def _do(self, dec, a):
        """Executa uma jogada (de qualquer assento) e, se ela tem efeito visivel, grava um QUADRO."""
        g = self.g
        p = dec.player
        self._before(dec)
        ph = dec.phase
        a = int(a)
        skip = ph in SELECT_ONLY or a == g.A_DONE and ph in (Phase.MOVE_SELECT, Phase.ATTUNE_SRC, Phase.UNDERWORLD_SRC)
        if ph == Phase.MOVE_DEST and a - g.A_CELL == dec.info.get("src"):
            skip = True                                           # a figura ficou onde estava
        hl = {"from": None, "to": None, "line": None, "edges": None}
        if g.A_CELL <= a < g.A_DONE:
            c = a - g.A_CELL
            if ph in (Phase.MOVE_DEST, Phase.PUSH_DEST, Phase.ATTUNE_DEST):
                hl["from"], hl["to"] = dec.info.get("src"), c
            else:
                hl["to"] = c
        if ph == Phase.CHOOSE_ACTION:
            hl["line"] = a - g.A_TRACK
        if ph == Phase.CAMEL_LINE and a > g.A_CAMEL:
            hl["edges"] = [[g.ax2i[x] for x in tuple(e)] for e in dec.info["lines"][a - g.A_CAMEL - 1]]
        if ph in SECRET_PHASES:
            text = "escolhe uma carta (em segredo)" if ph == Phase.BATTLE_CARD else "faz um lance (em segredo)"
        else:
            try:
                text = describe(g, dec, a)
            except Exception:                                      # noqa: BLE001
                text = f"acao {a}"
        dev0, alive0, ev0, cards0 = list(g.dev_pos), list(g.alive), g.event_idx, g.cur_cards
        merged0 = g.merged
        lines = [f"{seat_label(g, p)}: {text}"]
        g.step(a)
        if g.event_idx > ev0 and ev0 < len(EVENTS):
            lines.append(f">>> EVENTO {ev0 + 1}/18: {EVENT_TEXT[EVENTS[ev0]]}")
        if g.cur_cards is not None and g.cur_cards is not cards0 and g.cur_cards:
            shown = ", ".join(f"{seat_label(g, e)}: {'+'.join(CARD_NAMES[c] for c in cs)}"
                              for e, cs in g.cur_cards.items() if cs)
            if shown:
                lines.append(f"    cartas reveladas -> {shown}")
        diff = [(q, g.dev_pos[q] - dev0[q]) for q in range(g.P) if g.dev_pos[q] != dev0[q]]
        if diff and g.merged is merged0:
            lines.append("    Devocao: " + ", ".join(f"J{q} {d:+d} (-> {g.dev_pos[q]})" for q, d in diff))
        if g.merged is not merged0 and g.merged is not None:
            lines.append(f"    FUSAO: J{g.merged[1]} foi absorvido por J{g.merged[0]}")
        for q in range(g.P):
            if alive0[q] and not g.alive[q] and (g.merged is None or q not in g.merged or g.rep[q] == q):
                if not (g.merged is not None and g.merged[1] == q):
                    lines.append(f"    {seat_label(g, q)} foi ESQUECIDO")
        if skip and len(lines) == 1:
            return
        if skip:
            lines = lines[1:]
        for ln in lines:
            self.say(ln)
        self.events.append({"actor": p, "phase": ph.name, "lines": lines, "hl": hl,
                            "slow": 0.55 if ph in (Phase.MOVE_DEST, Phase.ATTUNE_DEST) else 1.0,
                            "state": self.state_json(light=True)})

    def _run_ai(self):
        g = self.g
        guard = 0
        while not g.done and g.decision.player not in self.humans:
            dec = g.decision
            self._do(dec, self.ai_action(dec))
            guard += 1
            if guard > 100000:
                raise RuntimeError("loop das IAs")
        if g.done:
            self._announce_end()

    def _announce_end(self):
        g = self.g
        if getattr(self, "_end_said", None) is g:
            return
        self._end_said = g
        if g.winner is None:
            self.say("FIM: Egito ateu (todos os deuses foram esquecidos).")
        else:
            self.say(f"FIM: vence {seat_label(g, g.winner)}.")

    def act(self, seat, a):
        with self.lock:
            g = self.g
            if g is None or g.done:
                raise ValueError("nao ha partida em andamento")
            if seat not in self.humans:
                raise ValueError("esse assento e controlado pela IA")
            if g.decision.player != seat:
                raise ValueError(f"nao e a vez de J{seat} (agora e J{g.decision.player})")
            dec = g.decision
            if not (0 <= a < g.A_SIZE and dec.mask[a]):
                raise ValueError("acao ilegal")
            self._do(dec, a)
            self._run_ai()

    def payload(self, seat=None, since=0, gid=None):
        """Quadros novos (a partir de `since`) + estado do ponto de vista de `seat`."""
        with self.lock:
            if gid is not None and int(gid) != self.game_id:
                since = 0                                           # outra partida: recomeca
            since = max(0, min(int(since), len(self.events)))
            return {"gid": self.game_id, "next": len(self.events), "frames": self.events[since:],
                    "state": self.state_json(viewer=seat)}

    # ---------------- exportacao ----------------
    def board_json(self):
        b, g = self.board, AnkhGame("basic_2p", board=self.board)
        cells = [{"i": i, "col": rc[0], "line": rc[1], "r2": b._pos[rc][0], "ter": g.terrain[i]}
                 for i, rc in enumerate(b.cells)]
        river = []
        for e in b.river_edges:
            a, c = tuple(e)
            if a in g.ax2i and c in g.ax2i:
                river.append([g.ax2i[a], g.ax2i[c]])
        return {"cells": cells, "river": river, "ncols": b.ncols,
                "gods": GODS, "kinds": KIND_NAMES, "cards": CARD_NAMES, "card_bonus": CARD_BONUS,
                "powers": POWER_NAMES, "events": EVENTS, "top": TOP, "red": RED_SPACES,
                "action_start": ACTION_START, "action_end": ACTION_END}

    def options(self):
        return {"scenarios": {n: s["n_players"] for n, s in SCENARIOS.items()},
                "gods": GODS, "models": [os.path.basename(m) for m in self.models],
                "warnings": self.warnings, "lan": self.lan, "urls": self.urls}

    def _anchor(self, region):
        pos = [self.board._pos[self.board.cells[i]] for i in region]
        cr = sum(p[0] for p in pos) / len(pos)
        cc = sum(p[1] for p in pos) / len(pos)
        land = [i for i in region if self.g.is_land[i]]
        return min(land, key=lambda i: (self.board._pos[self.board.cells[i]][0] - cr) ** 2 * 0.5
                   + (self.board._pos[self.board.cells[i]][1] - cc) ** 2 * 2)

    def decision_json(self, viewer):
        g = self.g
        dec = g.decision
        if g.done or dec is None or dec.player != viewer or viewer not in self.humans:
            return None
        acts = []
        N = g.N
        ops = None
        if dec.phase == Phase.CAMEL_SWAP and self.camel_new:
            new = self.camel_new
            ops = [None]
            for x in new:
                for y in g.regions:
                    if y != x and not (y in new and new.index(y) < new.index(x)):
                        ops.append((x, y))
            ops = ops[:N_CHOICE]
        for a in np.flatnonzero(dec.mask):
            a = int(a)
            item = {"a": a}
            try:
                item["text"] = describe(g, dec, a)
            except Exception:                                      # noqa: BLE001
                item["text"] = f"acao {a}"
            if g.A_CELL <= a < g.A_DONE:
                item["cell"] = a - g.A_CELL
            elif dec.phase == Phase.BID:
                item["bid"] = a - g.A_BID
            elif dec.phase == Phase.BATTLE_CARD:
                item["card"] = a - g.A_CARD
            elif dec.phase == Phase.CAMEL_LINE and a > g.A_CAMEL:
                line = dec.info["lines"][a - g.A_CAMEL - 1]
                item["edges"] = [[g.ax2i[x] for x in tuple(e)] for e in line]
            elif dec.phase == Phase.CAMEL_KEEP and self.camel_new:
                item["region"] = sorted(self.camel_new[a - g.A_CHOICE])
                item["text"] = f"a regiao em destaque mantem o token de ordem antigo ({'A' if a == g.A_CHOICE else 'B'})"
            elif dec.phase == Phase.CAMEL_SWAP and ops:
                op = ops[a - g.A_CHOICE]
                if op is None:
                    item["text"] = "nao trocar tokens de ordem"
                else:
                    x, y = op
                    item["regions"] = [sorted(x), sorted(y)]
                    item["text"] = f"trocar token {g.tokens[x]} (regiao A) com token {g.tokens[y]} (regiao B)"
            elif dec.phase == Phase.UNLOCK_PICK:
                item["power"] = a - g.A_POWER
            acts.append(item)
        out = {"phase": dec.phase.name, "actions": acts, "src": dec.info.get("src"),
               "level": dec.info.get("level")}
        return out

    def state_json(self, light=False, viewer=None):
        with self.lock:
            g = self.g
            if g is None:
                return {"started": False}
            if viewer is None or viewer not in self.humans:
                viewer = self.humans[0]
            N = g.N
            cells = {}
            for i in range(N):
                c = {}
                if g.fig_owner[i] >= 0:
                    c["f"] = [g.fig_owner[i], g.fig_kind[i], int(g.fig_sun[i])]
                if g.claw[i] is not None:
                    d = g.claw[i]
                    c["cl"] = [j for j in (g.cyc_nb[i][d], g.cyc_nb[i][(d + 1) % 6]) if j >= 0]
                if g.mon_type[i] is not None:
                    c["m"] = [MON_TYPES.index(g.mon_type[i]), g.mon_owner[i]]
                if g.underworld[i]:
                    c["u"] = 1
                if c:
                    cells[str(i)] = c
            camels = [[g.ax2i[x] for x in tuple(e)] for e in g.camel_edges]
            tokens = [[self._anchor(r), t] for r, t in g.tokens.items()]
            players = []
            for p in range(g.P):
                e = g.rep[p]
                players.append({
                    "seat": p, "god": g.god[p], "god2": g.god2[e], "ent": e, "alive": bool(g.alive[e]),
                    "absorbed": e != p, "superior": bool(g.merged is not None and g.merged[0] == p),
                    "dev": g.dev_pos[e], "followers": g.followers[e], "pool": g.warriors_pool[e],
                    "board_w": g.board_warriors(e), "ankh": g.ankh_pool[e],
                    "powers": sorted(g.powers[e]), "unlock_next": g.unlock_next[e],
                    "hand_n": len(g.hand[e]), "used": list(g.used[e]), "gpool": list(g.gpool[e]),
                    "sun_left": g.sun_left[e], "uw_off": g.uw_off[e],
                    "trapped": len(g.trapped[e]), "amun_declared": bool(g.amun_declared.get(e, False)),
                    "dev_order": g.dev_key(e)[1] if g.alive[e] else -1,
                    "hand": sorted(g.hand[e]),          # publico: e o complemento das cartas usadas (viradas)
                })
            cur_cards = None
            if g.cur_cards:
                cur_cards = {str(e): list(cs) for e, cs in g.cur_cards.items()}
            pend = None if g.done or g.decision is None else g.decision.player
            s = {
                "started": True, "scenario": g.scenario, "P": g.P, "human": viewer, "humans": list(self.humans),
                "mode": self.mode, "gid": self.game_id,
                "pending": None if pend is None else {"seat": pend, "human": pend in self.humans},
                "seed": self.seed,
                "cells": cells, "camels": camels, "tokens": tokens, "players": players,
                "markers": list(g.markers), "event_idx": g.event_idx, "conflicts_done": g.conflicts_done,
                "cur": g.cur, "merged": list(g.merged) if g.merged is not None else None,
                "tiebreak_holder": g.tiebreak_holder, "tiebreak_available": bool(g.tiebreak_available),
                "supply": g.supply, "camel_supply": g.camel_supply,
                "g_card": {str(k): v for k, v in g.g_card.items()},
                "g_supply": {str(k): v for k, v in g.g_supply.items()},
                "cur_region": sorted(g.cur_region) if g.cur_region is not None else None,
                "cur_cards": cur_cards,
                "done": bool(g.done), "winner": g.winner,
                "decision": None if light else self.decision_json(viewer), "warnings": self.warnings,
                "ai": "aleatoria" if self.ai_kind == "random" else os.path.basename(self.models[int(self.ai_kind)]),
                "anubis_slots": ANUBIS_SLOTS,
            }
            if not light:
                s["log"] = self.log[-150:]
            if g.done:
                s["end_reason"] = g.stats.get("end_reason")
            return s


class Handler(BaseHTTPRequestHandler):
    session = None

    def log_message(self, *a):                       # silencia o log por requisicao
        pass

    def _send(self, code, body, ctype="application/json"):
        data = body if isinstance(body, bytes) else json.dumps(body).encode()
        self.send_response(code)
        self.send_header("Content-Type", ctype + "; charset=utf-8")
        self.send_header("Content-Length", str(len(data)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        s = Handler.session
        u = urlparse(self.path)
        q = {k: v[0] for k, v in parse_qs(u.query).items()}
        seat = int(q["seat"]) if q.get("seat", "").lstrip("-").isdigit() and int(q["seat"]) >= 0 else None
        if u.path in ("/", "/index.html"):
            with open(os.path.join(HERE, "play.html"), "rb") as f:
                self._send(200, f.read(), "text/html")
        elif u.path == "/api/board":
            self._send(200, s.board_json())
        elif u.path == "/api/options":
            self._send(200, s.options())
        elif u.path == "/api/state":
            self._send(200, s.payload(seat, since=10**9))
        elif u.path == "/api/poll":
            self._send(200, s.payload(seat, int(q.get("since", 0) or 0), q.get("gid")))
        else:
            self._send(404, {"erro": "nao encontrado"})

    def do_POST(self):
        s = Handler.session
        n = int(self.headers.get("Content-Length") or 0)
        try:
            body = json.loads(self.rfile.read(n) or b"{}")
            if self.path == "/api/new":
                s.new_game(body.get("scenario", "basic_2p"), body.get("seats"), body.get("ai"),
                           body.get("seed"), body.get("mode", "hot"))
                seat = body.get("seat")
                self._send(200, s.payload(seat if isinstance(seat, int) else None, 0))
            elif self.path == "/api/act":
                seat = int(body["seat"])
                s.act(seat, int(body["a"]))
                self._send(200, s.payload(seat, int(body.get("since", 0) or 0), body.get("gid")))
            else:
                self._send(404, {"erro": "nao encontrado"})
        except Exception as e:                       # noqa: BLE001
            self._send(400, {"erro": str(e)})


def lan_ips():
    ips = set()
    try:
        sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sk.connect(("10.255.255.255", 1))
        ips.add(sk.getsockname()[0])
        sk.close()
    except OSError:
        pass
    try:
        ips.add(socket.gethostbyname(socket.gethostname()))
    except OSError:
        pass
    return sorted(i for i in ips if not i.startswith("127."))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--models", default="", help="checkpoints .zip separados por virgula (vazio = IA aleatoria)")
    ap.add_argument("--port", type=int, default=8765)
    ap.add_argument("--device", default="cpu")
    ap.add_argument("--deterministic", action="store_true", help="a IA escolhe sempre a acao mais provavel")
    ap.add_argument("--no-browser", action="store_true")
    ap.add_argument("--lan", action="store_true",
                    help="aceita outros aparelhos da rede local (cada humano joga no seu); sem login: so em rede de confianca")
    a = ap.parse_args()
    models = [m for m in a.models.split(",") if m]
    for m in models:
        if not os.path.exists(os.path.expanduser(m)):
            print("AVISO: arquivo nao encontrado:", m)
    Handler.session = Session(models, a.device, a.deterministic)
    Handler.session.lan = a.lan
    srv = ThreadingHTTPServer(("0.0.0.0" if a.lan else "127.0.0.1", a.port), Handler)
    url = f"http://127.0.0.1:{a.port}"
    Handler.session.urls = [f"http://{ip}:{a.port}" for ip in lan_ips()] if a.lan else []
    print("Ankh rodando em", url, "(Ctrl+C para sair)")
    if a.lan:
        print("Rede local: abra num outro aparelho ->", ", ".join(Handler.session.urls) or "(nao consegui descobrir o IP; use ipconfig/ip a)")
        print("AVISO: nao ha senha; qualquer aparelho da rede consegue jogar por qualquer assento humano.")
    if not a.no_browser:
        threading.Timer(0.8, lambda: webbrowser.open(url)).start()
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        pass


if __name__ == "__main__":
    main()