#!/usr/bin/env python3
"""Publishes language packs: copies them to the web folder and writes and signs the pack catalog.

The app downloads packs from https://hoolang.app/data/packs/<id>/<version>/<path> and checks every
file against the size and SHA-256 fingerprint of a catalog it trusts: the one compiled into it
(`files/pack-catalog.json`) or a newer `catalog.json` from the web folder that carries a valid
signature (`catalog.json.sig`, ECDSA P-256 with SHA-256) of the HooLang catalog key. This script
writes both catalogs from the same files, so they always match, and signs the web one.

Usage: build-catalog.py --version 2026-11-20 --web <HooLangWeb>/public/data/packs \
           --catalog <app>/composeResources/files/pack-catalog.json \
           --key ~/androidworkspace/keystore/hoolang/pack-catalog-signing.pem [--merge] <pack dir>...
The name of a pack directory is the pack id (`de`, `de-cs`). Every file of the directory is
published; the limits are the ones the app enforces (see PackCatalog in the app).

Without --merge the catalog lists only the given packs. With --merge it keeps the other packs of the
existing catalog unchanged (their versions and fingerprints), so one pack can be added or updated
without republishing the rest. Every run raises the catalog's sequence by one: the app takes a
signed catalog only when its sequence is higher than that of the catalog it has.

With --app-only the packs are for the app's own catalog only (the English packs): their files go to
the web folder and their entries, marked `"appOnly": true`, into the app's catalog, while the web
catalog and its signature stay untouched. The signed web catalog is shared by every released app
version, and a version that still has English built in would take a listed `en` for a dictionary it
lacks. Later runs keep these entries in the app's catalog and out of the web one. Such a pack is
updated with an app release only.
"""
import argparse
import hashlib
import json
import re
import shutil
import subprocess
import sys
from pathlib import Path

MAX_FILE_BYTES = 25 * 1024 * 1024  # Cloudflare serves static files up to 25 MiB
MAX_PACK_BYTES = 64 * 1024 * 1024
MAX_FILES = 200
ID = re.compile(r"[a-z]{2}(-[a-z]{2})?")
VERSION = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
SEGMENT = re.compile(r"[a-z0-9][a-z0-9._-]*")
FORMAT = 2
PUBLIC_KEY = Path(__file__).with_name("catalog-signing-key.pub.pem")


def pack_files(directory):
    """The files of a pack as sorted (relative path, absolute path) pairs.

    Empty files are left out: a Latin table always has the 27 shard files, and a small table (the
    Swedish pronunciations have no word starting with q or x) can leave some of them empty. The app
    reads a shard that is not there as a letter without words, so nothing is lost.
    """
    files = [
        (path.relative_to(directory).as_posix(), path)
        for path in directory.rglob("*")
        if path.is_file()
        and not path.name.startswith("._")
        and path.name != ".DS_Store"
        and path.stat().st_size > 0
    ]
    return sorted(files)


def describe(directory, version):
    """The catalog entry of a pack, validated against the limits the app enforces."""
    pack_id = directory.name
    if not ID.fullmatch(pack_id):
        raise ValueError(f"Bad pack id: {pack_id}")
    if not VERSION.fullmatch(version):
        raise ValueError(f"Bad version: {version}")
    entries = []
    for relative, path in pack_files(directory):
        if not all(SEGMENT.fullmatch(part) for part in relative.split("/")):
            raise ValueError(f"Bad file path in {pack_id}: {relative}")
        data = path.read_bytes()
        if not 0 < len(data) <= MAX_FILE_BYTES:
            raise ValueError(f"Bad size of {pack_id}/{relative}: {len(data)}")
        entries.append(
            {"path": relative, "size": len(data), "sha256": hashlib.sha256(data).hexdigest()}
        )
    if not entries or len(entries) > MAX_FILES:
        raise ValueError(f"Bad number of files in {pack_id}")
    if "pack.json" not in {entry["path"] for entry in entries}:
        raise ValueError(f"{pack_id} has no pack.json")
    if sum(entry["size"] for entry in entries) > MAX_PACK_BYTES:
        raise ValueError(f"{pack_id} is too large")
    manifest = json.loads((directory / "pack.json").read_text(encoding="utf-8"))
    pack_format = manifest.get("format", FORMAT)
    if type(pack_format) is not int:
        raise ValueError(f"Bad pack format in {pack_id}: {pack_format}")
    result = {"id": pack_id, "version": version, "files": entries}
    if pack_format != FORMAT:
        result["format"] = pack_format
    return result


def merged(existing, packs):
    """The existing catalog's packs with the given ones added or replaced, sorted by id."""
    published = {pack["id"] for pack in packs}
    kept = [pack for pack in existing.get("packs", []) if pack["id"] not in published]
    return sorted(kept + packs, key=lambda pack: pack["id"])


def read_catalog(path):
    path = Path(path)
    return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}


def sign(catalog_path, key, public_key=PUBLIC_KEY):
    """Writes `<catalog>.sig` with openssl and checks it against the public key the app pins."""
    catalog_path = Path(catalog_path)
    signature = catalog_path.with_name(catalog_path.name + ".sig")
    subprocess.run(["openssl", "dgst", "-sha256", "-sign", str(key), "-out", str(signature),
                    str(catalog_path)], check=True)
    subprocess.run(["openssl", "dgst", "-sha256", "-verify", str(public_key), "-signature",
                    str(signature), str(catalog_path)], check=True, capture_output=True)
    return signature


def publish(directories, version, web_dir, catalog_path, merge=False, key=None,
            public_key=PUBLIC_KEY, app_only=False):
    """Copies the packs, writes the app's and the web's catalog and, with [key], signs the latter.

    Version folders that are on the web already are left alone: apps that were built with an older
    catalog still download from them. Publishing the same pack version again replaces its folder.
    With [app_only] the packs join the app's catalog only and the web catalog is not written.
    """
    packs = [describe(Path(directory), version) for directory in directories]
    for pack, directory in zip(packs, directories):
        target = Path(web_dir) / pack["id"] / version
        if target.exists():
            shutil.rmtree(target)
        for relative, path in pack_files(Path(directory)):
            (target / relative).parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(path, target / relative)
    existing = read_catalog(catalog_path)
    web_catalog = Path(web_dir) / "catalog.json"
    published = max(existing.get("sequence", 0), read_catalog(web_catalog).get("sequence", 0))
    if app_only:
        # The app keeps the sequence of the web catalog, which stays as it is.
        packs = merged(existing, [dict(pack, appOnly=True) for pack in packs])
        catalog = {"format": FORMAT, "sequence": published, "packs": packs}
        Path(catalog_path).write_text(serialized(catalog), encoding="utf-8")
        return catalog
    if merge:
        packs = merged(existing, packs)
    catalog = {"format": FORMAT, "sequence": published + 1, "packs": packs}
    Path(catalog_path).write_text(serialized(catalog), encoding="utf-8")
    for_web = dict(catalog, packs=[pack for pack in packs if not pack.get("appOnly")])
    web_catalog.write_text(serialized(for_web), encoding="utf-8")
    if key is not None:
        sign(web_catalog, key, public_key)
    return catalog


def serialized(catalog):
    return json.dumps(catalog, indent=1, ensure_ascii=False) + "\n"


def main(argv):
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--version", required=True)
    parser.add_argument("--web", required=True)
    parser.add_argument("--catalog", required=True)
    parser.add_argument("--key", help="private key (PEM) the web catalog is signed with")
    parser.add_argument("--merge", action="store_true", help="keep the other packs of the catalog")
    parser.add_argument("--app-only", action="store_true",
                        help="list the packs in the app's catalog only; the web catalog stays")
    parser.add_argument("packs", nargs="+")
    args = parser.parse_args(argv)
    if not args.app_only and args.key is None:
        parser.error("--key is required unless --app-only is given")
    catalog = publish(args.packs, args.version, args.web, args.catalog, args.merge, args.key,
                      app_only=args.app_only)
    signed = "web catalog untouched" if args.app_only else "signed"
    print(f"catalog sequence {catalog['sequence']}, {signed}")
    for pack in catalog["packs"]:
        total = sum(entry["size"] for entry in pack["files"])
        scope = " (app only)" if pack.get("appOnly") else ""
        print(f"{pack['id']} {pack['version']}: {len(pack['files'])} files, {total} bytes{scope}")


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