#!/usr/bin/env python3
"""
Validate all RU robust certificates found under sources/ru/ against the schema.
"""
from __future__ import annotations
import os, json, glob, argparse

try:
    import jsonschema  # type: ignore
except Exception:
    jsonschema = None

def load(p):
    with open(p,"r",encoding="utf-8") as f:
        return json.load(f)

def main()->int:
    ap=argparse.ArgumentParser()
    ap.add_argument("--root", default=".", help="Project root containing sources/")
    args=ap.parse_args()
    schema_path=os.path.join(args.root,"sources","ru","robust_certificate_schema.json")
    schema=load(schema_path)
    certs=sorted(glob.glob(os.path.join(args.root,"sources","ru","robust_certificate_*.json")))
    certs=[c for c in certs if "_schema" not in os.path.basename(c)]
    # exclude any files under examples/
    certs=[c for c in certs if os.path.sep+"examples"+os.path.sep not in c]

    if not certs:
        print("No robust_certificate_*.json files found.")
        return 1
    ok_all=True
    for c in certs:
        inst=load(c)
        name=os.path.basename(c)
        if jsonschema is None:
            # fallback: required keys only
            missing=[k for k in schema.get("required",[]) if k not in inst]
            if missing:
                ok_all=False
                print(f"{name}: FAIL missing keys {missing}")
            else:
                print(f"{name}: PASS (fallback required-keys check; install jsonschema for full validation)")
            continue
        try:
            jsonschema.validate(instance=inst, schema=schema)
            print(f"{name}: PASS")
        except Exception as e:
            ok_all=False
            print(f"{name}: FAIL {e}")
    return 0 if ok_all else 2

if __name__=="__main__":
    raise SystemExit(main())
