#!/usr/bin/env python3
"""Validateur de schéma pour les manifestes du store Ordissimo (*.json).

Usage:
    python3 validate_store.py [fichier.json ...]      # défaut: tous les *.json du dossier
    python3 validate_store.py --check-urls            # vérifie aussi que les URLs répondent (HTTP 200)

Code de sortie 0 si aucun fichier n'a d'ERREUR, 1 sinon. Les WARN ne font pas échouer.
"""
import sys
import os
import re
import json
import glob

KNOWN_ARCHS = {"arm64-v8a", "armeabi-v7a", "x86", "x86_64"}
KNOWN_DEVICES = {"phone", "tablet"}
MD5_RE = re.compile(r"^[0-9a-fA-F]{32}$")
URL_RE = re.compile(r"^https?://", re.IGNORECASE)


class Reporter:
    def __init__(self):
        self.errors = []
        self.warnings = []

    def err(self, path, msg):
        self.errors.append(f"{path}: {msg}")

    def warn(self, path, msg):
        self.warnings.append(f"{path}: {msg}")


def check_type(rep, where, value, expected, type_name):
    if not isinstance(value, expected):
        rep.err(where, f"doit être de type {type_name}, trouvé {type(value).__name__}")
        return False
    return True


def check_apk_entry(rep, where, entry, urls):
    """Vérifie un objet {url, md5, splits?}."""
    if not check_type(rep, where, entry, dict, "objet"):
        return
    if "url" not in entry:
        rep.err(where, "champ 'url' manquant")
    elif check_type(rep, where + ".url", entry["url"], str, "string"):
        if not URL_RE.match(entry["url"]):
            rep.err(where + ".url", f"URL invalide: {entry['url']!r}")
        # double slash dans le chemin (hors schéma)
        if re.search(r"[^:]//", entry["url"].split("://", 1)[-1]):
            rep.warn(where + ".url", f"double slash dans le chemin: {entry['url']}")
        urls.add(entry["url"])
    if "md5" not in entry:
        rep.err(where, "champ 'md5' manquant")
    elif check_type(rep, where + ".md5", entry["md5"], str, "string"):
        if not MD5_RE.match(entry["md5"]):
            rep.err(where + ".md5", f"md5 invalide (attendu 32 hex): {entry['md5']!r}")
        elif entry["md5"] != entry["md5"].lower():
            rep.warn(where + ".md5", "md5 en majuscules (préférer minuscules)")
    if "splits" in entry:
        if check_type(rep, where + ".splits", entry["splits"], list, "array"):
            if not entry["splits"]:
                rep.warn(where + ".splits", "tableau 'splits' vide")
            for i, sp in enumerate(entry["splits"]):
                check_apk_entry(rep, f"{where}.splits[{i}]", sp, urls)


def check_details(rep, where, details):
    if not check_type(rep, where, details, dict, "objet"):
        return
    if not details:
        rep.err(where, "'details' ne doit pas être vide")
    for loc, val in details.items():
        w = f"{where}.{loc}"
        if not check_type(rep, w, val, dict, "objet"):
            continue
        for k in ("label", "description"):
            if k not in val:
                rep.err(w, f"champ '{k}' manquant")
            elif not isinstance(val[k], str):
                rep.err(w + f".{k}", "doit être une string")


def check_app(rep, where, app, packages, urls):
    if not check_type(rep, where, app, dict, "objet"):
        return
    # champs requis et leurs types
    required = {
        "package": str,
        "icon": str,
        "versionCode": int,
        "versionName": str,
        "minSdkVersion": int,
        "maxSdkVersion": int,
        "details": dict,
        "apks": dict,
        "devices": list,
    }
    for field, typ in required.items():
        if field not in app:
            rep.err(where, f"champ requis '{field}' manquant")
            continue
        # bool est sous-type de int en Python: l'exclure pour les entiers
        if typ is int and isinstance(app[field], bool):
            rep.err(where + f".{field}", "doit être un entier, trouvé booléen")
            continue
        check_type(rep, where + f".{field}", app[field], typ, typ.__name__)

    pkg = app.get("package")
    label = pkg if isinstance(pkg, str) else where

    if isinstance(app.get("icon"), str) and not URL_RE.match(app["icon"]):
        rep.err(where + ".icon", f"URL d'icône invalide: {app['icon']!r}")
    if isinstance(app.get("icon"), str) and re.search(r"[^:]//", app["icon"].split("://", 1)[-1]):
        rep.warn(where + ".icon", f"double slash dans le chemin: {app['icon']}")

    if "autoInstall" in app and not isinstance(app["autoInstall"], bool):
        rep.err(where + ".autoInstall", "doit être un booléen")

    if isinstance(app.get("minSdkVersion"), int) and isinstance(app.get("maxSdkVersion"), int):
        if not isinstance(app["minSdkVersion"], bool) and not isinstance(app["maxSdkVersion"], bool):
            if app["minSdkVersion"] > app["maxSdkVersion"]:
                rep.err(where, f"minSdkVersion ({app['minSdkVersion']}) > maxSdkVersion ({app['maxSdkVersion']})")

    if isinstance(app.get("details"), dict):
        check_details(rep, f"app[{label}].details", app["details"])

    if isinstance(app.get("apks"), dict):
        if not app["apks"]:
            rep.err(f"app[{label}].apks", "doit contenir au moins une architecture")
        for arch, entry in app["apks"].items():
            if arch not in KNOWN_ARCHS:
                rep.warn(f"app[{label}].apks", f"architecture inconnue: {arch!r}")
            check_apk_entry(rep, f"app[{label}].apks.{arch}", entry, urls)

    devs = app.get("devices")
    if isinstance(devs, list):
        if not devs:
            rep.err(f"app[{label}].devices", "ne doit pas être vide")
        for d in devs:
            if d not in KNOWN_DEVICES:
                rep.warn(f"app[{label}].devices", f"device inconnu: {d!r}")
        # doublon package + device qui se recouvrent
        if isinstance(pkg, str):
            for d in devs:
                key = (pkg, d)
                if key in packages:
                    rep.warn(f"app[{label}]", f"package en double pour le device '{d}'")
                packages.add(key)


def validate_file(path, rep, check_urls, url_bag):
    with open(path, encoding="utf-8") as f:
        raw = f.read()
    try:
        data = json.loads(raw)
    except json.JSONDecodeError as e:
        rep.err(path, f"JSON invalide: ligne {e.lineno} col {e.colno}: {e.msg}")
        return

    if not check_type(rep, path, data, dict, "objet"):
        return
    for field, typ, tn in (("version", int, "entier"), ("message", str, "string"), ("apps", list, "array")):
        if field not in data:
            rep.err(path, f"champ racine '{field}' manquant")
        elif not isinstance(data[field], typ) or (typ is int and isinstance(data[field], bool)):
            rep.err(path, f"champ racine '{field}' doit être {tn}")

    apps = data.get("apps")
    if isinstance(apps, list):
        packages = set()
        for i, app in enumerate(apps):
            check_app(rep, f"{path} apps[{i}]", app, packages, url_bag)


def head_ok(url):
    import urllib.request
    for method in ("HEAD", "GET"):
        try:
            req = urllib.request.Request(url, method=method)
            with urllib.request.urlopen(req, timeout=15) as r:
                return 200 <= r.status < 400
        except Exception:
            continue
    return False


def main():
    argv = sys.argv[1:]
    check_urls = "--check-urls" in argv
    files = [a for a in argv if not a.startswith("--")]
    base = os.path.dirname(os.path.abspath(__file__))
    if not files:
        files = sorted(glob.glob(os.path.join(base, "*.json")))

    overall_ok = True
    for path in files:
        rep = Reporter()
        url_bag = set()
        validate_file(path, rep, check_urls, url_bag)

        name = os.path.basename(path)
        if rep.errors:
            overall_ok = False
            print(f"\n✗ {name} — {len(rep.errors)} erreur(s), {len(rep.warnings)} warning(s)")
            for m in rep.errors:
                print(f"    ERROR  {m}")
        else:
            print(f"\n✓ {name} — OK ({len(rep.warnings)} warning(s))")
        for m in rep.warnings:
            print(f"    WARN   {m}")

        if check_urls and not rep.errors:
            bad = [u for u in sorted(url_bag) if not head_ok(u)]
            if bad:
                overall_ok = False
                print(f"    {len(bad)} URL(s) injoignable(s):")
                for u in bad:
                    print(f"    ERROR  URL injoignable: {u}")

    print()
    sys.exit(0 if overall_ok else 1)


if __name__ == "__main__":
    main()
