#!/usr/bin/env python3
"""Runs tiktok-test-cases.json against tiktok_post_check.py. MIT License, APIWings.
Usage: python test_tiktok_check.py
"""
import json
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from tiktok_post_check import check, chunk_plan  # noqa: E402


def load(name):
    with open(os.path.join(HERE, name), encoding="utf-8") as fh:
        return json.load(fh)


cases = load("tiktok-test-cases.json")["cases"]
passed = 0
fails = []
for c in cases:
    e = c["expect"]
    if "chunk" in c:
        p = chunk_plan(c["chunk"]["size"], c["chunk"]["chunk"])
        ok = p["valid"] == e["valid"]
        if ok and e["valid"]:
            ok = (p["total_chunk_count"] == e["total_chunk_count"] and p["final_chunk_bytes"] == e["final_chunk_bytes"]
                  and p["content_ranges"][-1] == e["last_range"])
    else:
        plan = load(c["file"]) if "file" in c else c["plan"]
        r = check(plan)
        ok = r["status"] == e["status"]
        issues = list(r["app_issues"])
        for p in r["posts"]:
            issues.extend(p["issues"])
        if "codes" in e:
            ok = ok and sorted(set(i["code"] for i in issues)) == e["codes"]
        if "issue_count" in e:
            ok = ok and len(issues) == e["issue_count"]
        if "posts" in e:
            ok = ok and all(e["posts"].get(p["id"]) == p["status"] for p in r["posts"])
    if ok:
        passed += 1
    else:
        fails.append(c["name"])
for f in fails[:20]:
    print("FAIL: " + f)
print("%d of %d cases pass" % (passed, len(cases)))
sys.exit(0 if passed == len(cases) else 1)
