"""Compress PNGs"""
priority = -1
from tqdm import tqdm

import os
import subprocess


def compress_pngs(root_dir: str, verbose: bool = False):
    compressed_files = []
    for dirpath, _, filenames in os.walk(root_dir):
        for filename in filenames:
            if filename.lower().endswith(".png"):
                filepath = os.path.join(dirpath, filename)
                if verbose: tqdm.write(f"Сжимаю: {filepath}")
                try:
                    assert subprocess.run(
                        [
                            "pngquant",
                            "--force",
                            "--ext",
                            ".png",
                            "--quality=65-90",
                            filepath,
                        ],
                        capture_output=True,
                    ).returncode in [0, 99]
                    compressed_files.append(filepath)
                except subprocess.CalledProcessError as e:
                    tqdm.write(f"Ошибка при сжатии {filepath}: {e}")
    return compressed_files


def apply(config: dict) -> bool:
    files = compress_pngs("./decompiled", config.get("verbose", False))
    return len(files) > 0 and any(files)
