#!/usr/bin/env python3
"""
Analyse the dependencies installed in every Python virtualenv on my computer.

This gets a complete list of dependencies in each environment, then
prints a list of dependencies and the versions installed.
"""

from collections import Counter, defaultdict
from pathlib import Path
import re
import subprocess

from chives.text import coloured

if __name__ == "__main__":
    venv_path = Path("/tmp/depanalysis/venv.txt")
    venv_path.parent.mkdir(exist_ok=True)

    output = subprocess.check_output(
        "get_all_venv_deps", text=True, stderr=subprocess.DEVNULL
    )
    venv_path.write_text(output)

    all_versions = defaultdict(list)
    for line in output.splitlines():
        if not re.search(r"==[0-9]", line):
            continue

        package, version = line.strip().split("==")
        all_versions[package].append(version)

    for package, versions in sorted(all_versions.items(), key=lambda kv: len(kv[1])):
        tally = Counter(versions)

        if len(tally) == 1:
            print(f"{len(versions):3d}  {package} {versions[0]}")
        else:
            # Break each version into a tuple of ints, then sort them.
            # This will break for non-numeric versions but it's fine for
            # now, and makes it easy to spot outdated packages.
            sorted_versions = sorted(
                tally.items(), key=lambda kv: tuple([int(p) for p in kv[0].split(".")])
            )
            version_info = ", ".join(
                f"{v_str} ({count})" for v_str, count in sorted_versions
            )
            print(f"{len(versions):3d}  {package} {coloured(version_info, 'blue')}")

    subprocess.check_call(["mate", str(venv_path)])

    unique_versions = sum(len(set(v)) for v in all_versions.values())
    print(f"{len(all_versions)} packages, {unique_versions} unique versions")
