"""Independent policy, ledger, and provider for the W1 credits-1 vocabulary."""
import sqlite3
from wire import Invalid, canonical, digest, require
from storage import Store

INHERITED = ("root","service","account","project","purpose","budget","policy","epoch")
ACTOR = ("holder","key","gen","service")


def matches(a, b, keys):
    return all(a[k] == b[k] for k in keys)


def current(obj, now):
    return obj["nbf"] <= now < obj["exp"]


class Domain:
    def __init__(self, peer, path, setup):
        self.peer, self.suite = peer, peer.suite
        self.f, self.binding = self.suite.fx, peer.binding
        self.store = Store(path,self.f)
        if setup in ("root","active"):
            result = self.run({"do":"admit","approval":"approval","receipt":"root","join":"join-root","runtime":"runtime-root"})
            require(result == "ADMITTED","root initialization")
        if setup == "active":
            for worker in ("a","b"):
                name = "grant-"+worker
                result = self.run({"do":"delegate","grant":name,"join":"join-"+name,"runtime":"runtime-"+worker,
                                   "authorization":"ask-"+name})
                require(result == "GRANTED","child initialization")
        require(setup in ("empty","root","active"),"unknown reset state")

    @staticmethod
    def registered(db, terms):
        item = db.execute("SELECT gen,kid FROM generation WHERE holder=?",(terms["holder"],)).fetchone()
        return item is not None and tuple(item) == (terms["gen"],terms["key"])

    def terms_ok(self, t, now, epoch):
        require(t["service"] == self.f["origin"] and t["account"] == "lab" and t["project"] == "p7" and
                t["purpose"] == "simulation" and t["budget"] == "pool-p7" and t["policy"] == "credits-1",
                "unrecognized resource vocabulary")
        require(current(t,now) and t["epoch"] == epoch and t["depth"] <= 8 and
                t["per"] <= t["limit"] <= self.store.ceiling and t["actions"] == sorted(set(t["actions"]))
                and set(t["actions"]) <= {"charge","lookup"}, "ineligible grant terms")

    def appraisal(self, db, token, terms, now):
        app = self.binding.open_token(token,"appraisal")
        require(matches(app,terms,ACTOR) and current(app,now) and app["policy"] == "runtime-1" and
                self.registered(db,terms), "stale actor or appraisal")
        return app

    def join(self, label, terms, now):
        signed = self.peer.claim(label,"join")
        require(matches(signed,terms,ACTOR) and current(signed,now) and
                signed["termsHash"] == digest(canonical(terms)), "join proof")

    def inspect_chain(self, db, tokens, now):
        epoch = db.execute("SELECT epoch FROM policy").fetchone()[0]
        require(1 <= len(tokens) <= 9,"chain length")
        ids, keys, lineage = set(), set(), []
        for i, token in enumerate(tokens):
            t = self.binding.open_token(token,"root" if i == 0 else "grant")["terms"]
            self.terms_ok(t,now,epoch)
            reg = db.execute("SELECT compact FROM grants WHERE id=?",(t["id"],)).fetchone()
            require(reg and reg[0] == token and t["id"] not in ids and t["key"] not in keys, "unregistered or repeated grant")
            if lineage:
                parent = lineage[-1]
                self.attenuated(t,parent)
                require(t["survive"] or self.registered(db,parent), "inactive parent")
            else:
                require(t["id"] == t["root"] and t["parent"] == "", "missing root")
            ids.add(t["id"]); keys.add(t["key"]); lineage.append(t)
        return lineage

    @staticmethod
    def attenuated(t, parent):
        require(t["parent"] == parent["id"] and t["id"] != parent["id"] and
                all(t[k] != parent[k] for k in ("key","holder")) and matches(t,parent,INHERITED) and
                set(t["actions"]) <= set(parent["actions"]) and t["depth"] < parent["depth"] and
                t["per"] <= parent["per"] and t["limit"] <= parent["limit"] and
                parent["nbf"] <= t["nbf"] < t["exp"] <= parent["exp"] and
                (not t["survive"] or parent["survive"]), "child expands parent authority")

    def register(self, db, compact, t):
        prev = db.execute("SELECT compact FROM grants WHERE id=?",(t["id"],)).fetchone()
        require(prev is None or prev[0] == compact,"grant ID redefinition")
        db.execute("INSERT OR IGNORE INTO grants VALUES(?,?)",(t["id"],compact))

    def issue(self, db, s, now):
        ctrl = db.execute("SELECT * FROM policy").fetchone()
        gate = db.execute("SELECT * FROM provider.gates").fetchone()
        require(not ctrl["revoked"] and not gate["held"] and gate["connected"], "issuance unavailable")
        is_root = s["do"] == "admit"
        label = s["receipt"] if is_root else s["grant"]
        record = self.peer.claim(label,"root" if is_root else "grant")
        t = record["terms"]
        self.terms_ok(t,now,ctrl["epoch"])
        self.join(s["join"],t,now)
        self.appraisal(db,self.peer.objects[s["runtime"]],t,now)
        if is_root:
            consent = self.peer.claim(s["approval"],"approval")
            require(record["approvalHash"] == digest(self.peer.objects[s["approval"]].encode("ascii")) and
                    consent["subject"] == record["subject"] == "operator" and
                    consent["challenge"] == record["challenge"] == self.f["challenge"] and
                    consent["terms"] == t and t["root"] == t["id"] and not t["parent"],"approval mismatch")
            if db.execute("SELECT 1 FROM challenges WHERE id=?",(consent["challenge"],)).fetchone():
                return "REPLAY"
            db.execute("INSERT INTO challenges VALUES(?)",(consent["challenge"],))
        else:
            ancestry, seen, parent_id = [], {t["id"]}, t["parent"]
            while parent_id:
                require(parent_id not in seen and len(ancestry) < 8,"cyclic or excessive lineage")
                seen.add(parent_id)
                row = db.execute("SELECT compact FROM grants WHERE id=?",(parent_id,)).fetchone()
                require(row,"unknown parent")
                ancestor = self.binding.open_token(row[0])["terms"]
                ancestry.insert(0,row[0]); parent_id = ancestor["parent"]
            parents = self.inspect_chain(db,ancestry,now)
            parent = parents[-1]
            self.attenuated(t,parent)
            approval = self.peer.claim(s["authorization"],"request_grant")
            require(self.registered(db,parent) and t["key"] not in {p["key"] for p in parents} and
                    current(approval,now) and approval["parent"] == parent["id"] and
                    matches(approval,parent,("service","key","gen")) and
                    approval["joinHash"] == digest(self.peer.objects[s["join"]].encode("ascii")) and
                    approval["termsHash"] == digest(canonical(t)), "invalid parent authorization")
        self.register(db,self.peer.objects[label],t)
        return "ADMITTED" if is_root else "GRANTED"

    def authorize(self, db, msg, now, permit_label):
        gate = db.execute("SELECT * FROM provider.gates").fetchone()
        if gate["held"]:
            return "HELD"
        q = msg.body
        t = self.inspect_chain(db,q["chain"],now)[-1]
        intent = q["intent"]
        require(matches(q,t,("holder","gen","key")) and matches(intent,t,("root","service","account","project","purpose")),
                "actor or resource mismatch")
        app = self.appraisal(db,q["appraisal"],t,now)
        if not gate["connected"]:
            return "HELD"
        policy = db.execute("SELECT * FROM policy").fetchone()
        if policy["revoked"]:
            return "DENIED"
        if not db.execute("INSERT OR IGNORE INTO records VALUES(?,?,?)",(q["key"],q["gen"],q["record"])).rowcount:
            return "REPLAY"
        permission = "lookup" if q["mode"] == "lookup" else intent["action"]
        if (permission not in t["actions"] or intent["action"] != "charge" or
                not 0 < intent["units"] <= t["per"] or (q["mode"] == "execute" and not gate["allowCharge"])):
            return "DENIED"
        ih = digest(canonical(intent))
        prev = db.execute("SELECT * FROM operations WHERE op=?",(q["op"],)).fetchone()
        if prev:
            if "lookup" not in t["actions"] or (prev["holder"],prev["root"]) != (q["holder"],intent["root"]):
                return "DENIED"
            if prev["intent"] != ih:
                return "CONFLICT"
            terminal = db.execute("SELECT kind FROM provider.terminal WHERE op=?",(q["op"],)).fetchone()
            if terminal:
                return "RECONCILED" if terminal[0] == "outcome" else "CLOSED"
            original = self.binding.open_token(prev["permit"],"permit")
            if (prev["status"] == "reserved" and original["iat"] <= now < original["exp"] and
                    matches(original,q,("key","gen")) and original["fence"] == policy["fence"]):
                return "RESERVED"
            return "UNCERTAIN"
        if q["mode"] == "lookup":
            return "DENIED"
        reserved,settled,_ = self.store.credits(db)
        if reserved+settled+intent["units"] > min(self.store.ceiling,t["limit"]):
            return "BUDGET"
        require(permit_label, "missing permit")
        permit = self.peer.claim(permit_label,"permit")
        require(matches(permit,q,("op","holder","gen","key")) and
                matches(permit,intent,("root","service","account","project","units")) and
                matches(permit,t,("budget","policy","epoch")) and permit["intentHash"] == ih and
                permit["fence"] == policy["fence"] and permit["iat"] == now and
                now < permit["exp"] <= min(now+5, t["exp"], app["exp"]), "invalid reservation")
        # The vector fixes the opaque permit ID. Derive the other claims at the
        # reservation point from the verified actor, intent, account and clock.
        issued = {k:q[k] for k in ("op","holder","key","gen")}
        issued.update({k:intent[k] for k in ("root","service","account","project","units")})
        issued.update({k:t[k] for k in ("budget","policy","epoch")})
        issued.update(kind="permit", p=self.f["profile"], id=permit["id"], intentHash=ih,
                      fence=policy["fence"],iat=now,exp=min(now+5,t["exp"],app["exp"]))
        signed = self.binding.token(issued,self.f["signers"]["permit"])
        require(signed == self.peer.objects[permit_label], "peer and local permit disagree")
        require(not db.execute("SELECT 1 FROM operations WHERE pid=?",(issued["id"],)).fetchone() and
                not db.execute("SELECT 1 FROM provider.accepted WHERE op=? OR pid=?",(q["op"],issued["id"])).fetchone(),
                "conflicting operation or permit ID")
        db.execute("INSERT INTO operations VALUES(?,?,?,?,?,?,?,'reserved')",
                   (q["op"],q["holder"],intent["root"],ih,permit["id"],signed,intent["units"]))
        db.execute("INSERT INTO provider.accepted VALUES(?,?,?)",(q["op"],permit["id"],signed))
        return "RESERVED"

    def request(self, s, now, barrier=None):
        try:
            envelope = self.peer.message(s["message"],now)
        except Invalid:
            return "INVALID"
        if barrier is not None:
            barrier.wait(timeout=10)
        with self.store.transaction() as db:
            try:
                decision = self.authorize(db,envelope,now,s.get("permit"))
            except Invalid:
                decision = "DENIED"
            db.execute("INSERT INTO provider.routes VALUES(?,?,?,?)",
                       (envelope.target,envelope.body["op"],envelope.body["intent"]["action"],decision))
            if decision != "HELD":
                self.store.remember(db)
            return decision

    def terminal(self, s, now, close):
        with self.store.provider_transaction() as db:
            gate = db.execute("SELECT * FROM gates").fetchone()
            if gate["held"]:
                return "HELD"
            if close:
                signed = self.peer.objects[s["closure"]]
                evidence = self.binding.open_token(signed,"closure")
                row = db.execute("SELECT compact FROM accepted WHERE op=?",(evidence["op"],)).fetchone()
                require(row,"unknown permit")
                permit = self.binding.open_token(row[0],"permit")
                require(permit["epoch"] == gate["epoch"],"closure epoch")
                kind = "closure"
            else:
                permit = self.peer.claim(s["permit"],"permit")
                row = db.execute("SELECT compact FROM accepted WHERE op=?",(permit["op"],)).fetchone()
                actor = db.execute("SELECT gen,kid FROM generation WHERE holder=?",(permit["holder"],)).fetchone()
                require(row and row[0] == self.peer.objects[s["permit"]] and gate["allowCharge"] and
                        gate["epoch"] == permit["epoch"] and permit["fence"] >= gate["fence"] and
                        actor and tuple(actor) == (permit["gen"],permit["key"]), "provider gate")
                kind = "outcome"
            old = db.execute("SELECT kind,compact FROM terminal WHERE op=?",(permit["op"],)).fetchone()
            if old and old["kind"] != kind:
                return "DENIED"
            if not close:
                error = s.get("uncertainty",0)
                if now-error < permit["iat"] or now+error >= permit["exp"]:
                    return "EXPIRED"
                if old:
                    return "ALREADY_COMMITTED"
                signed = self.peer.objects[s["outcome"]]
                evidence = self.binding.open_token(signed,"outcome")
            require(evidence["at"] == now and evidence["permit"] == permit["id"] and
                    matches(evidence,permit,("op","holder","root","service","account","project","units","epoch","intentHash")),
                    "resource evidence mismatch")
            if close:
                require(not old or old["compact"] == signed,"conflicting closure")
            else:
                require(evidence["row"] == "row-"+permit["op"],"provider row identity")
            # Create the provider's own statement for the event being committed
            # and bind it to the same database transaction as the account row.
            issued = {k:permit[k] for k in ("op","holder","root","service","account","project","units","epoch","intentHash")}
            issued.update(p=self.f["profile"],kind=kind,permit=permit["id"],at=now)
            if not close:
                issued["row"] = "row-"+permit["op"]
            local_receipt = self.binding.token(issued,self.f["signers"][kind])
            require(signed == local_receipt,"peer and local resource evidence disagree")
            db.execute("INSERT OR IGNORE INTO terminal VALUES(?,?,?,?,?,?)",
                       (permit["op"],kind,permit["units"],local_receipt,now,issued.get("row")))
            return "CLOSED" if close else "COMMITTED"

    def account(self, db, s, close):
        gate = db.execute("SELECT * FROM provider.gates").fetchone()
        if gate["held"] or not gate["connected"]:
            return "HELD"
        kind = "closure" if close else "outcome"
        token = self.peer.objects[s[kind]]
        proof = self.binding.open_token(token,kind)
        op = db.execute("SELECT * FROM operations WHERE op=?",(proof["op"],)).fetchone()
        row = db.execute("SELECT compact,kind FROM provider.terminal WHERE op=?",(proof["op"],)).fetchone()
        require(op and row and (row["compact"],row["kind"]) == (token,kind) and
                (op["pid"],op["intent"],op["units"],op["holder"]) ==
                (proof["permit"],proof["intentHash"],proof["units"],proof["holder"]), "accounting evidence")
        status = "closed" if close else "settled"
        if op["status"] == status:
            return "ALREADY_RELEASED" if close else "ALREADY_SETTLED"
        require(op["status"] in ("reserved","uncertain"),"terminal accounting conflict")
        db.execute("UPDATE operations SET status=? WHERE op=?",(status,proof["op"]))
        return "RELEASED" if close else "SETTLED"

    def control(self, db, s, now):
        action = s["do"]
        if action != "recover" and db.execute("SELECT held FROM provider.gates").fetchone()[0]:
            return "HELD"
        if action in ("admit","delegate"):
            return self.issue(db,s,now)
        if action in ("settle","release"):
            return self.account(db,s,action=="release")
        if action == "drop":
            require(db.execute("UPDATE operations SET status='uncertain' WHERE op=? AND status='reserved'",
                               (s["op"],)).rowcount,"no outstanding reservation")
            return "UNCERTAIN"
        if action == "rotate":
            require(s["key"] in self.f["keys"],"unknown generation key")
            for table in ("main.generation","provider.generation"):
                require(db.execute(f"UPDATE {table} SET kid=?,gen=? WHERE holder=? AND gen<?",
                                   (s["key"],s["gen"],s["holder"],s["gen"])).rowcount,"generation does not advance")
            return "ROTATED"
        if action == "ownerPolicy":
            db.execute("UPDATE provider.gates SET allowCharge=?",(int(s["allowCharge"]),))
            return "UPDATED"
        if action == "isolate":
            db.execute("UPDATE provider.gates SET connected=0")
            return "ISOLATED"
        if action == "reconnect":
            db.execute("UPDATE provider.gates SET connected=1,fence=(SELECT fence FROM policy)")
            return "CONNECTED"
        if action == "revoke":
            rev = self.peer.claim(s["object"],"revocation")
            root = db.execute("SELECT 1 FROM grants WHERE id=?",(rev["root"],)).fetchone()
            require(root and rev["root"] == "r1" and rev["at"] == now and
                    db.execute("UPDATE policy SET revoked=1,fence=? WHERE epoch=? AND fence<?",
                               (rev["fence"],rev["epoch"],rev["fence"])).rowcount, "invalid revocation")
            db.execute("UPDATE provider.gates SET fence=? WHERE connected=1",(rev["fence"],))
            return "REVOKED"
        if action in ("anchor","recover"):
            ck = self.peer.claim(s["checkpoint"],"checkpoint")
            require((ck["root"],ck["account"],ck["service"]) == ("r1","lab",self.f["origin"]), "checkpoint scope")
            compact = self.peer.objects[s["checkpoint"]]
            if action == "recover":
                return self.store.recover(db,compact,ck,self.peer.claim(s["authorization"],"recovery"),s["journal"])
            require(ck["epoch"] == db.execute("SELECT epoch FROM policy").fetchone()[0],"checkpoint epoch")
            return self.store.seal(db,compact,ck)
        raise ValueError("Unknown control "+action)

    def run(self, s):
        action = s["do"]
        now = self.suite.clock+s.get("at",0)
        if action in ("wire","response"):
            try:
                self.peer.message(s["message"],now,s.get("request"))
                return "VALID"
            except Invalid:
                return "INVALID"
        if action == "request":
            return self.request(s,now)
        if action == "snapshot":
            return self.store.snapshot(s["label"])
        if action == "restorePrimary":
            return self.store.restore_primary(s["label"])
        try:
            if action in ("commit","close"):
                return self.terminal(s,now,action=="close")
            with self.store.transaction() as db:
                decision = self.control(db,s,now)
                if action != "recover" and decision != "HELD":
                    self.store.remember(db)
                return decision
        except (Invalid, sqlite3.IntegrityError):
            return "HELD" if action == "recover" else "DENIED"

