#!/usr/bin/env python3
"""91-cz.cn self-authored teaching example, version 0.1.0, MIT.
Reads the site's own ZIP fixture without extracting or executing members.
"""
import json
import sys
import zipfile
from pathlib import PurePosixPath


def ledger(filename):
    with zipfile.ZipFile(filename) as archive:
        names = sorted(item.filename for item in archive.infolist() if not item.is_dir())
        for name in names:
            path = PurePosixPath(name)
            if path.is_absolute() or '..' in path.parts:
                raise ValueError('Archive contains a non-relative member path')
        required = ['teaching-source/VERSION', 'teaching-source/LICENSE.txt', 'teaching-source/README.txt']
        if not all(name in names for name in required):
            raise ValueError('This teaching fixture requires VERSION, LICENSE.txt and README.txt')
        version = archive.read(required[0]).decode('utf-8').strip()
        return dict(project='site-owned-ledger-demo', version=version,
                    license_path=required[1], files=names, file_count=len(names),
                    scope='Self-authored teaching data, not an unidentified 9.1 product')


if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python3 archive-ledger.py teaching-source-0.1.0.zip')
    print(json.dumps(ledger(sys.argv[1]), ensure_ascii=False, indent=2))
