# Two-player playthrough of The Hollow Hill against a FRESH database.
#   BASE=http://127.0.0.1:8099 python3 tests/playthrough.py
# Pass FAST=1 to skip the 21-second wait for the torch to respawn.
import os, re, sys, time, json, http.cookiejar, urllib.request, urllib.parse

BASE = os.environ.get("BASE", "http://127.0.0.1:8099")
fails = 0

class Player:
    def __init__(self, name):
        self.name = name
        self.op = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()), urllib.request.ProxyHandler({}))
        self.csrf = ""
        self.since = 0

    def page(self, path, data=None):
        body = urllib.parse.urlencode(data).encode() if data is not None else None
        r = self.op.open(BASE + path, body)
        html = r.read().decode()
        m = re.search(r'(?:name="_csrf" value|data-csrf)="([0-9a-f]+)"', html)
        if m: self.csrf = m.group(1)
        return r.geturl(), html

    def register(self, pw="lantern-light"):
        self.page("/register")
        return self.page("/register", {"_csrf": self.csrf, "name": self.name, "password": pw})

    def do(self, cmd):
        body = urllib.parse.urlencode({"_csrf": self.csrf, "cmd": cmd}).encode()
        d = json.loads(self.op.open(BASE + "/api/cmd", body).read().decode())
        if d.get("room", {}).get("last", 0) > self.since: self.since = d["room"]["last"]
        text = "\n".join(l["s"] for l in d["lines"])
        print(f"  [{self.name}] > {cmd}\n" + "\n".join("      " + l for l in text.split("\n")))
        return text, d

    def poll(self):
        d = json.loads(self.op.open(BASE + f"/api/poll?since={self.since}").read().decode())
        self.since = max(self.since, d["last"])
        text = "\n".join(l["s"] for l in d["lines"])
        print(f"  [{self.name}] (poll)\n" + "\n".join("      " + l for l in text.split("\n")))
        return text

def check(cond, label):
    global fails
    print(("PASS " if cond else "FAIL ") + label)
    if not cond: fails += 1

a, b = Player("Doyle"), Player("Mara")
u, html = a.register()
check(u.endswith("/play") and 'id="game"' in html, "register lands on the play screen")
u, html = b.register()
p = Player("rat"); u, html = p.register()
check("taken by something in the world" in html, "names of world things are refused")

t, d = a.do("look")
check("Village Square" in t and "Mara is here." in t, "Doyle sees the square and Mara")
check(set(d["room"]["exits"]) == {"north", "east", "west", "south", "northeast", "down"}, "exit buttons")
t, _ = a.do("read board"); check("Brother Anselm" in t, "read the notice board")
t, _ = a.do("d"); check("sheer drop" in t, "well needs a rope")
t, _ = a.do("say hello Mara")
t = b.poll(); check('Doyle says, "hello Mara"' in t, "Mara hears Doyle speak")

# Brambles
for c in ["n", "n"]: t, _ = a.do(c)
t, _ = a.do("n"); check("too thick" in t, "brambles block the gate")
t, _ = a.do("cut brambles"); check("You need a blade" in t, "cutting barehanded fails with a hint")
for c in ["s", "s", "w"]: a.do(c)
t, d = a.do("take sickle"); check("You take the rusty sickle" in t, "take sickle")
t, _ = a.do("get apple"); check("apple" in t, "take apple")
for c in ["e", "n", "n"]: a.do(c)
t, _ = a.do("cut brambles"); check("(with the rusty sickle)" in t and "path opens north" in t, "sickle cuts brambles (auto-used)")
t, _ = a.do("n"); check("Tunnel Mouth" in t, "through the gate")
t, _ = a.do("e"); check("pitch dark" in t, "dark tunnel is dark without a light")
t, _ = a.do("d"); check("blackness" in t, "can't go deeper in the dark")
t, _ = a.do("take all"); check("dirt" in t, "can't find things in the dark")
for c in ["w", "s", "s", "s", "e"]: t, _ = a.do(c)
check("The Smithy" in t, "back at the smithy")

# Torches, dagger, rope
t, _ = a.do("take torch"); t, _ = a.do("light torch"); check("forge" in t, "light torch at the forge")
t, _ = a.do("take dagger"); t, _ = a.do("take rope")
t, _ = a.do("i"); check("a torch (burning)" in t and "(5 of 6)" in t, "inventory shows 5 of 6 and the burning torch")

# Mara arrives: no torch left on the rack
t, _ = b.do("e"); check("Doyle is here, carrying a light" in t, "Mara sees Doyle's torch")
check("You see a torch" not in t, "Doyle took the only torch")
t = a.poll(); check("Mara arrives from the west" in t, "Doyle sees Mara arrive")
if not os.environ.get("FAST"):
    print("  (waiting 21s for a new torch on the rack…)"); time.sleep(21)
    t, _ = b.do("look"); check("You see a torch" in t, "torch respawns on the rack")
    t, _ = b.do("take torch")
else:
    t, _ = a.do("give torch to mara")
    a.do("take torch")
t, _ = a.do("w")
t, _ = b.do("w")
t, _ = b.do("light torch"); check("Doyle's flame" in t or "already" in t, "Mara lights her torch from Doyle's flame")

# Well
t, _ = a.do("tie rope"); check("(with" not in t and "Anyone can climb down" in t, "tie rope to well (well is right there)")
t = b.poll(); check("ties a rope to the well" in t, "Mara sees the rope tied")
t, _ = a.do("climb down"); check("Bottom of the Well" in t and "iron key" in t, "climb down the well")
t, _ = a.do("take key"); a.do("u")

# Crypt
t, _ = a.do("s"); t, _ = a.do("d"); check("locked" in t, "crypt is locked")
t, _ = a.do("open door"); check("(with the iron key)" in t and "Stairs lead down" in t, "open door uses the key")
t, _ = b.do("s"); check("door stands open" in t, "Mara sees the crypt door open")
t, _ = a.do("d"); check("Crypt" in t and "silver bell" in t, "crypt lit by Doyle's torch, bell visible")
t, _ = a.do("take bell")
t, _ = a.do("take all"); check("hands are full" in t or "nothing here" in t.lower(), "carry limit / nothing left")
t, _ = b.do("d")
for c in ["w", "n"]:
    a.do(c); b.do(c)

# The slab needs two
t, _ = a.do("push slab"); check("One pair of hands is not enough" in t, "slab won't move for one")
t = b.poll(); check("needs a second pair of hands" in t, "Mara sees Doyle straining")
t, _ = b.do("push slab"); check("slides aside" in t, "two people move the slab")
t = a.poll(); check("archway north is open" in t, "Doyle sees it open")
t, _ = b.do("n"); check("Hall of Echoes" in t and "moonstone" in t, "Hall of Echoes")
t, _ = b.do("take moonstone"); b.do("s"); b.do("s"); a.do("s")

# The rat
t, _ = a.do("u"); check("fat rat" in t, "rat guards the tunnel")
t, _ = b.do("u")
t, _ = a.do("e"); check("will not let you past" in t, "rat blocks the way")
t, _ = a.do("give apple to mara"); check("You give Mara an apple" in t, "give an item to another player")
t = b.poll(); check("Doyle gives you an apple" in t, "Mara is told she got the apple")
t, _ = b.do("feed rat"); check("(with the apple)" in t and "waddles off" in t, "feed the rat an apple")
t, _ = a.do("e"); check("Hollow Shrine" in t, "past the rat")
b.do("e")

# Finale
t, _ = a.do("ring bell"); check("Something belongs in it" in t, "bell does nothing without the moonstone")
t, _ = b.do("put moonstone in hollow"); check("settles into the hollow" in t, "moonstone in the hollow")
t, _ = a.do("ring bell"); check("Chapter 1 complete" in t, "ring the bell: chapter complete")
t = b.poll(); check("Chapter 1 complete" in t, "Mara sees the ending")
t, _ = b.do("journal"); check("rang the bell" in t, "Mara's journal got the entry too")
t, _ = a.do("journal"); check("Places discovered:" in t, "journal shows discoveries")

# Kill the rat with a dagger (bring it back first)
a.do("w")
import sqlite3
db = os.environ.get("DB")
if db:
    con = sqlite3.connect(db); con.execute("DELETE FROM world_state WHERE k='rat_gone'"); con.commit(); con.close()
    t, _ = a.do("kill rat"); check("(with the dagger)" in t and "goes still" in t, "kill the rat with the dagger")
    t, _ = b.do("w")

# Light and darkness, shared
t, _ = b.do("douse torch"); check("smother" in t, "Mara puts out her torch")
t, _ = a.do("drop torch"); t, _ = a.do("look"); check("You see" in t and "torch (burning)" in t, "a dropped burning torch lights the room")
t, _ = b.do("look"); check("Dark Tunnel" in t and "pitch dark" not in t, "Mara can see by the torch on the ground")

# Parser odds and ends
t, _ = a.do("dance"); check("don't know how" in t, "unknown verb")
t, _ = a.do("x mara"); check("Mara is carrying" in t, "examine another player")
t, _ = a.do("use sickle on mara"); check(t != "", "nonsense use handled")
t, _ = a.do("who"); check("Doyle" in t and "Mara" in t, "who lists both")
t, _ = a.do("help"); check("How to play" in t, "help")

print(f"\n{fails} failure(s)")
sys.exit(1 if fails else 0)
