#!/usr/bin/env python3
import sys
import apt_pkg
from collections import OrderedDict

apt_pkg.init()

def parse_packages(f):
    packages = []
    with apt_pkg.TagFile(f) as tag_file:
        for section in tag_file:
            pkg = {k: section[k] for k in section.keys()}
            packages.append(pkg)
    return packages

def keep_latest(packages):
    latest = OrderedDict()
    for pkg in packages:
        name = pkg.get('Package', '')
        version = pkg.get('Version', '')
        if name not in latest or apt_pkg.version_compare(version, latest[name]['Version']) > 0:
            latest[name] = pkg
    return list(latest.values())

def format_package(pkg):
    lines = []
    for key, value in pkg.items():
        lines.append(f'{key}: {value}')
    return '\n'.join(lines) + '\n'

def main():
    input_file = sys.argv[1] if len(sys.argv) > 1 else '-'
    if input_file == '-':
        f = sys.stdin
    else:
        f = open(input_file, 'r')

    packages = parse_packages(f)
    f.close()

    latest = keep_latest(packages)

    for pkg in latest:
        sys.stdout.write(format_package(pkg) + '\n')

if __name__ == '__main__':
    main()
