"""Runs review-test-cases.json against meta_app_review_check.py. Usage: python test_review_check.py"""
import copy
import json
import sys
from pathlib import Path

from meta_app_review_check import check_submission, codes_of

HERE = Path(__file__).resolve().parent


def read(f):
    return json.loads((HERE / f).read_text(encoding="utf-8"))


T = read("review-test-cases.json")
BASE = read(T["base_file"])


def build(c):
    if "plan" in c:
        return copy.deepcopy(c["plan"])
    if "plan_file" in c:
        return read(c["plan_file"])
    plan = copy.deepcopy(BASE)
    by_name = {p["name"]: p for p in plan["permissions"]}  # original names, stable after renames
    ops = c.get("ops") or [op for m in c["mutations"] for op in T["mutations"][m]["ops"]]
    for op in ops:
        if op["op"] == "remove_perm":
            p = by_name[op["name"]]
            plan["permissions"] = [x for x in plan["permissions"] if x is not p]
        elif op["op"] == "add_perm":
            p = copy.deepcopy(op["perm"])
            plan["permissions"].append(p)
            by_name[p["name"]] = p
        elif op["op"] == "set":
            path = [by_name[k[5:]] if k.startswith("perm:") else k for k in op["path"]]
            target = plan
            for k in path[:-1]:
                if isinstance(k, dict):
                    target = k
                    continue
                if not isinstance(target.get(k), dict):
                    target[k] = {}
                target = target[k]
            target[path[-1]] = copy.deepcopy(op["value"])
    return plan


passed, fails = 0, []
for c in T["cases"]:
    rep = check_submission(build(c))
    got = codes_of(rep)
    if got == c["expected"] and (not c.get("result") or c["result"] == rep["result"]):
        passed += 1
    else:
        fails.append(f"{c['id']}\n  expected {', '.join(c['expected'])}\n  got      {', '.join(got)} ({rep['result']})")
for f in fails[:20]:
    print("FAIL", f)
print(f"{passed} of {len(T['cases'])} cases pass")
sys.exit(1 if fails else 0)
