#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2026 ICSL FZE
"""Checks Goethe packages against the JSON Schemas of Goethe Format 1 (docs/format/schema). Standard library only.

    python3 check_schema.py PROJECT...            PROJECT: a .goethe or .lexwrite folder, a .goethex file, or a .json file
    python3 check_schema.py PROJECT... --strict   also lists keys the schemas do not describe (and fails on them)

It knows the part of JSON Schema 2020-12 the two schemas use: $ref to #/$defs, type, enum, const, properties, required,
additionalProperties, propertyNames, items, minItems, maxItems, minimum, maximum, exclusiveMinimum, pattern,
format "date-time", anyOf, oneOf. Exit status 0 when every file is valid.

Licence: MIT (see LICENSE beside this file and ../LICENSE.md). Copyright (c) 2026 ICSL FZE.
"""

import json
import os
import re
import sys
import zipfile

HERE = os.path.dirname(os.path.abspath(__file__))
SCHEMAS = os.path.join(os.path.dirname(HERE), "schema")
DATE_TIME = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$")


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


def is_type(value, t):
    if t == "object":
        return isinstance(value, dict)
    if t == "array":
        return isinstance(value, list)
    if t == "string":
        return isinstance(value, str)
    if t == "boolean":
        return isinstance(value, bool)
    if t == "integer":
        return isinstance(value, int) and not isinstance(value, bool)
    if t == "number":
        return isinstance(value, (int, float)) and not isinstance(value, bool)
    if t == "null":
        return value is None
    return False


class Validator:
    def __init__(self, root):
        self.root = root

    def resolve(self, schema):
        while "$ref" in schema:
            target = schema["$ref"]
            if not target.startswith("#/$defs/"):
                raise ValueError("only local references: %s" % target)
            schema = self.root["$defs"][target[len("#/$defs/"):]]
        return schema

    def validate(self, value, schema, path, errors, extra):
        """Adds what is wrong to `errors`; keys the schema does not describe to `extra` (when it is a list)"""
        schema = self.resolve(schema)
        types = schema.get("type")
        if types is not None:
            types = types if isinstance(types, list) else [types]
            if not any(is_type(value, t) for t in types):
                errors.append("%s: %s instead of %s" % (path or "/", type(value).__name__, "/".join(types)))
                return
        if "enum" in schema and value not in schema["enum"]:
            errors.append("%s: %r is none of %s" % (path or "/", value, schema["enum"]))
        if "const" in schema and value != schema["const"]:
            errors.append("%s: %r instead of %r" % (path or "/", value, schema["const"]))
        if isinstance(value, str):
            if "pattern" in schema and not re.search(schema["pattern"], value):
                errors.append("%s: %r does not match %s" % (path or "/", value, schema["pattern"]))
            if schema.get("format") == "date-time" and not DATE_TIME.match(value):
                errors.append("%s: %r is no date-time" % (path or "/", value))
        if is_type(value, "number"):
            if "minimum" in schema and value < schema["minimum"]:
                errors.append("%s: %r below %r" % (path or "/", value, schema["minimum"]))
            if "maximum" in schema and value > schema["maximum"]:
                errors.append("%s: %r above %r" % (path or "/", value, schema["maximum"]))
            if "exclusiveMinimum" in schema and value <= schema["exclusiveMinimum"]:
                errors.append("%s: %r not above %r" % (path or "/", value, schema["exclusiveMinimum"]))
        if isinstance(value, dict):
            props = schema.get("properties", {})
            for key in schema.get("required", []):
                if key not in value:
                    errors.append("%s: required key %r missing" % (path or "/", key))
            for key, v in value.items():
                child = path + "/" + key
                if "propertyNames" in schema:
                    self.validate(key, schema["propertyNames"], child + " (name)", errors, None)
                if key in props:
                    self.validate(v, props[key], child, errors, extra)
                elif isinstance(schema.get("additionalProperties"), dict):
                    self.validate(v, schema["additionalProperties"], child, errors, extra)
                elif schema.get("additionalProperties") is False:
                    errors.append("%s: key not allowed" % child)
                elif props and extra is not None:
                    extra.append(child)
        if isinstance(value, list):
            if "minItems" in schema and len(value) < schema["minItems"]:
                errors.append("%s: fewer than %d items" % (path or "/", schema["minItems"]))
            if "maxItems" in schema and len(value) > schema["maxItems"]:
                errors.append("%s: more than %d items" % (path or "/", schema["maxItems"]))
            if "items" in schema:
                for k, v in enumerate(value):
                    self.validate(v, schema["items"], "%s/%d" % (path, k), errors, extra)
        for word in ("anyOf", "oneOf"):
            if word in schema:
                matching = []
                for branch in schema[word]:
                    trial = []
                    self.validate(value, branch, path, trial, None)
                    if not trial:
                        matching.append(branch)
                if not matching or (word == "oneOf" and len(matching) > 1):
                    errors.append("%s: matches %d of the %s cases" % (path or "/", len(matching), word))
                elif extra is not None:
                    self.validate(value, matching[0], path, [], extra)


def documents(target):
    """(label, kind, parsed JSON) of a package, an exchange file, or a JSON file"""
    if os.path.isdir(target):
        for name, kind in (("project.json", "project"), ("manifest.json", "manifest")):
            p = os.path.join(target, name)
            if os.path.isfile(p):
                with open(p, encoding="utf-8") as f:
                    yield target + "/" + name, kind, json.load(f)
    elif zipfile.is_zipfile(target):
        with zipfile.ZipFile(target) as z:
            names = set(z.namelist())
            for name, kind in (("project.json", "project"), ("manifest.json", "manifest")):
                if name in names:
                    yield target + ":" + name, kind, json.loads(z.read(name).decode("utf-8"))
    else:
        with open(target, encoding="utf-8") as f:
            data = json.load(f)
        yield target, "manifest" if "readableFrom" in data and "tree" not in data else "project", data


def main(argv):
    strict = "--strict" in argv
    targets = [a for a in argv if not a.startswith("--")]
    if not targets:
        sys.stderr.write(__doc__)
        return 2
    validators = {"project": Validator(load("project.schema.json")), "manifest": Validator(load("manifest.schema.json"))}
    failed = checked = undocumented = 0
    for target in targets:
        for label, kind, data in documents(target):
            v = validators[kind]
            errors, extra = [], [] if strict else None
            v.validate(data, v.root, "", errors, extra)
            checked += 1
            if errors or extra:
                failed += 1 if errors or strict else 0
                for line in errors[:20]:
                    print("ERROR        %s: %s" % (label, line))
                for line in sorted(set(re.sub(r"/\d+", "/[]", x) for x in (extra or [])))[:40]:
                    print("UNDESCRIBED  %s: %s" % (label, line))
                undocumented += len(extra or [])
            else:
                print("OK           %s" % label)
    print("%d files checked, %d with findings%s" % (checked, failed, (", %d keys not described" % undocumented) if strict else ""))
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
