#!/usr/bin/env python3
"""Inventory a specific runtime; copy its notices without modifying the runtime."""
import argparse
import hashlib
import json
import shutil
from email.parser import Parser
from pathlib import Path


def sha256(path):
    digest = hashlib.sha256()
    with path.open('rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            digest.update(chunk)
    return digest.hexdigest()


def is_notice(path):
    name = path.name.lower()
    return any(word in name for word in ('license', 'licence', 'copying', 'copyright', 'notice')) and path.suffix not in ('.py', '.pyc', '.so', '.png', '.json', '.csv')


def collect(runtime, output):
    runtime, output = runtime.resolve(), output.resolve()
    notices, packages = [], []
    for path in sorted(runtime.rglob('*')):
        if not path.is_file():
            continue
        relative = path.relative_to(runtime).as_posix()
        if is_notice(path) and path.stat().st_size < 2_000_000:
            # Binary libraries and program data are never included as notice text.
            data = path.read_bytes()
            if b'\0' in data:
                continue
            target = output / 'runtime-notices' / relative
            target.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(path, target)
            notices.append(dict(path=relative, sha256=sha256(path)))
        if path.name == 'METADATA' and path.parent.name.endswith('.dist-info'):
            meta = Parser().parsestr(path.read_text(errors='replace'))
            license_name = meta.get('License-Expression') or meta.get('License') or '; '.join(x for x in meta.get_all('Classifier', []) if x.startswith('License ::'))
            packages.append(dict(name=meta['Name'], version=meta['Version'], license=license_name,
                                 metadata=relative, metadata_sha256=sha256(path),
                                 homepage=meta.get('Home-page'), project_urls=meta.get_all('Project-URL', [])))
    libraries = [dict(path=p.relative_to(runtime).as_posix(), sha256=sha256(p))
                 for p in sorted(runtime.rglob('*')) if p.is_file() and p.suffix in ('.dylib', '.so')]
    inventory = dict(format_version=1, packages=packages, notices=notices, native_libraries=libraries)
    output.mkdir(parents=True, exist_ok=True)
    (output / 'runtime-inventory.json').write_text(json.dumps(inventory, ensure_ascii=False, indent=2) + '\n')
    lines = ['TimbrAI — third-party runtime components',
             'This inventory is descriptive; it does not replace the full licenses.',
             'Exact original notices are preserved in runtime-notices/.', '']
    for package in packages:
        lines += [package['name'] + ' ' + package['version'], package['license'] or 'See upstream notices', '']
    (output / 'THIRD-PARTY-NOTICES.txt').write_text('\n'.join(lines))
    print(json.dumps(dict(packages=len(packages), notices=len(notices), native_libraries=len(libraries))))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('runtime', type=Path)
    parser.add_argument('output', type=Path)
    args = parser.parse_args()
    collect(args.runtime, args.output)
