"""cabinet + policy: two tiny languages for the demo "one rule, three cabinets".

A cabinet is an application of one department. Its program (language cabinet) lists the department's own checks.
A policy rule (language policy) is a company-wide rule with a scope: which cabinets it applies to.
The handler evaluates deals: for each deal, the cabinet's own checks and every policy rule in scope fire or not,
and the verdict is the strictest outcome. Everything is data; no code is expressed in either language.

Deal fields: client (text), amount (number), discount_pct, payment_days, delivery_days, prepayment_pct (numbers),
country (text), has_penalty_clause (bool).

cabinet program: {"name": "Finance", "key": "finance", "checks": [ {"id": "f1", "when": <cond>, "then": "forbid|warn|approve_by_head", "say": "..."} ]}
policy rule:     {"id": "r1", "scope": ["finance", "lawyer"], "when": <cond>, "then": "forbid|warn|approve_by_head", "say": "..."}
cond:            {"field": <deal field>, "op": ">|>=|<|<=|==|!=|in|not_in", "value": number|text|bool|list}
Pure Python, standard library only, no backslashes.
"""
import hashlib
import json

FIELDS = {"client": "text", "amount": "number", "discount_pct": "number", "payment_days": "number", "delivery_days": "number", "prepayment_pct": "number", "country": "text", "has_penalty_clause": "bool"}
OPS = (">", ">=", "<", "<=", "==", "!=", "in", "not_in")
OUTCOMES = ("forbid", "approve_by_head", "warn")
SEVERITY = {"forbid": 3, "approve_by_head": 2, "warn": 1, "ok": 0}
CABINETS = ("lawyer", "finance", "logistics")
MAX_CHECKS = 8
MAX_RULES = 12


def _cond_ok(c):
    if not isinstance(c, dict) or set(c) != {"field", "op", "value"}:
        return False, "condition needs exactly field, op, value"
    f, op, v = c["field"], c["op"], c["value"]
    if f not in FIELDS:
        return False, "unknown field '%s'; fields: %s" % (f, ", ".join(FIELDS))
    if op not in OPS:
        return False, "unknown op '%s'" % op
    kind = FIELDS[f]
    if op in ("in", "not_in"):
        if not isinstance(v, list) or not v or len(v) > 20 or not all(isinstance(x, (str, int, float)) and not isinstance(x, bool) for x in v):
            return False, "'%s' needs a list of up to 20 values" % op
        return True, "ok"
    if kind == "number" and (not isinstance(v, (int, float)) or isinstance(v, bool)):
        return False, "field '%s' compares with a number" % f
    if kind == "text" and (not isinstance(v, str) or not 0 < len(v) <= 60):
        return False, "field '%s' compares with text up to 60 characters" % f
    if kind == "bool" and (not isinstance(v, bool) or op not in ("==", "!=")):
        return False, "field '%s' compares with true or false using == or !=" % f
    return True, "ok"


def _rule_ok(r, i, need_scope):
    if not isinstance(r, dict):
        return False, "rule %d must be an object" % i
    allowed = {"id", "when", "then", "say"} | ({"scope"} if need_scope else set())
    if set(r) - allowed or not {"id", "when", "then", "say"} <= set(r):
        return False, "rule %d: fields id, when, then, say%s only" % (i, ", scope" if need_scope else "")
    if not isinstance(r["id"], str) or not 0 < len(r["id"]) <= 24:
        return False, "rule %d: id is a short text" % i
    if r["then"] not in OUTCOMES:
        return False, "rule %d: then must be forbid, approve_by_head or warn" % i
    if not isinstance(r["say"], str) or not 0 < len(r["say"]) <= 140:
        return False, "rule %d: say is text up to 140 characters" % i
    if need_scope:
        sc = r.get("scope")
        if not isinstance(sc, list) or not sc or not all(s in CABINETS for s in sc):
            return False, "rule %d: scope is a list of cabinets from %s" % (i, ", ".join(CABINETS))
    ok, why = _cond_ok(r["when"])
    return (True, "ok") if ok else (False, "rule %d: %s" % (i, why))


def validate_cabinet(program):
    if not isinstance(program, dict) or set(program) - {"name", "key", "checks"} or not {"name", "key", "checks"} <= set(program):
        return False, "a cabinet is an object with name, key, checks"
    if program["key"] not in CABINETS:
        return False, "key must be one of " + ", ".join(CABINETS)
    if not isinstance(program["name"], str) or not 0 < len(program["name"]) <= 40:
        return False, "name is a short text"
    checks = program["checks"]
    if not isinstance(checks, list) or len(checks) > MAX_CHECKS:
        return False, "checks: a list of up to %d" % MAX_CHECKS
    for i, c in enumerate(checks, 1):
        ok, why = _rule_ok(c, i, False)
        if not ok:
            return False, why
    return True, "ok"


def validate_rules(rules):
    if not isinstance(rules, list) or len(rules) > MAX_RULES:
        return False, "rules: a list of up to %d" % MAX_RULES
    for i, r in enumerate(rules, 1):
        ok, why = _rule_ok(r, i, True)
        if not ok:
            return False, why
    return True, "ok"


def holds(cond, deal):
    v = deal.get(cond["field"])
    op, t = cond["op"], cond["value"]
    if v is None:
        return False
    if op == "in":
        return v in t
    if op == "not_in":
        return v not in t
    if isinstance(v, bool) or isinstance(t, bool):
        return (v == t) if op == "==" else (v != t) if op == "!=" else False
    if isinstance(v, str) or isinstance(t, str):
        v, t = str(v).lower(), str(t).lower()
        return (v == t) if op == "==" else (v != t) if op == "!=" else False
    return {">": v > t, ">=": v >= t, "<": v < t, "<=": v <= t, "==": v == t, "!=": v != t}[op]


def evaluate(program, rules, deals):
    """For each deal: which own checks and which policy rules (in scope) fired; verdict = strictest outcome."""
    out = []
    key = program["key"]
    in_scope = [r for r in rules if key in r["scope"]]
    for d in deals:
        fired = []
        for c in program["checks"]:
            if holds(c["when"], d):
                fired.append({"source": "cabinet", "id": c["id"], "then": c["then"], "say": c["say"]})
        for r in in_scope:
            if holds(r["when"], d):
                fired.append({"source": "policy", "id": r["id"], "then": r["then"], "say": r["say"]})
        verdict = "ok"
        for f in fired:
            if SEVERITY[f["then"]] > SEVERITY[verdict]:
                verdict = f["then"]
        out.append({"deal": d.get("id"), "verdict": verdict, "fired": fired})
    return {"cabinet": key, "name": program["name"], "rules_in_scope": [r["id"] for r in in_scope], "results": out}


def sha(obj):
    return hashlib.sha256(json.dumps(obj, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()


DEALS = [
    {"id": "d1", "client": "Aurora Retail", "amount": 48000, "discount_pct": 8, "payment_days": 30, "delivery_days": 5, "prepayment_pct": 30, "country": "DE", "has_penalty_clause": True},
    {"id": "d2", "client": "Bolt Logistics", "amount": 120000, "discount_pct": 15, "payment_days": 45, "delivery_days": 3, "prepayment_pct": 0, "country": "PL", "has_penalty_clause": False},
    {"id": "d3", "client": "Cedar Clinics", "amount": 9500, "discount_pct": 12, "payment_days": 14, "delivery_days": 10, "prepayment_pct": 100, "country": "AT", "has_penalty_clause": True},
    {"id": "d4", "client": "Delta Foods", "amount": 260000, "discount_pct": 5, "payment_days": 90, "delivery_days": 2, "prepayment_pct": 10, "country": "TR", "has_penalty_clause": False},
]

CABINET_PROGRAMS = {
    "lawyer": {"name": "Lawyer", "key": "lawyer", "checks": [
        {"id": "l1", "when": {"field": "has_penalty_clause", "op": "==", "value": False}, "then": "warn", "say": "contract has no penalty clause"},
        {"id": "l2", "when": {"field": "payment_days", "op": ">", "value": 60}, "then": "approve_by_head", "say": "payment term over 60 days needs the head of legal"}]},
    "finance": {"name": "Finance", "key": "finance", "checks": [
        {"id": "f1", "when": {"field": "prepayment_pct", "op": "<", "value": 20}, "then": "warn", "say": "prepayment under 20%"},
        {"id": "f2", "when": {"field": "amount", "op": ">", "value": 200000}, "then": "approve_by_head", "say": "deal over 200 000 needs the CFO"}]},
    "logistics": {"name": "Logistics", "key": "logistics", "checks": [
        {"id": "g1", "when": {"field": "delivery_days", "op": "<", "value": 3}, "then": "warn", "say": "delivery under 3 days: express rate applies"},
        {"id": "g2", "when": {"field": "country", "op": "in", "value": ["TR", "KZ", "UZ"]}, "then": "approve_by_head", "say": "customs route: head of logistics signs"}]},
}

DEFAULT_RULES = [
    {"id": "p0", "scope": ["lawyer", "finance"], "when": {"field": "payment_days", "op": ">", "value": 60}, "then": "approve_by_head", "say": "company rule: payment terms over 60 days need approval"},
]


def check_rule(rule):
    ok, why = validate_rules([rule])
    if not ok:
        return False, {"grammar": why}
    report = {"grammar": "ok", "affects": {}}
    for key, prog in CABINET_PROGRAMS.items():
        before = evaluate(prog, [], DEALS)
        after = evaluate(prog, [rule], DEALS)
        changed = [b["deal"] for b, a in zip(before["results"], after["results"]) if b["verdict"] != a["verdict"] or len(b["fired"]) != len(a["fired"])]
        report["affects"][key] = changed
    return True, report


if __name__ == "__main__":
    r = {"id": "r1", "scope": ["lawyer", "finance", "logistics"], "when": {"field": "discount_pct", "op": ">", "value": 10}, "then": "forbid", "say": "discounts over 10% are forbidden"}
    print(validate_rules([r]))
    for k, p in CABINET_PROGRAMS.items():
        e = evaluate(p, DEFAULT_RULES + [r], DEALS)
        print(k, [(x["deal"], x["verdict"], [f["id"] for f in x["fired"]]) for x in e["results"]])
    print(check_rule(r)[1])
    print(validate_rules([{"id": "x", "scope": ["finance"], "when": {"field": "discount_pct", "op": ">", "value": "eval(1)"}, "then": "forbid", "say": "x"}]))
