#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Remove generated packaging intermediates after installer builds."""

from __future__ import annotations

import shutil
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]


def _is_inside_root(path: Path) -> bool:
    try:
        path.resolve().relative_to(ROOT.resolve())
        return True
    except ValueError:
        return False


def _remove_dir(path: Path) -> None:
    if path.exists() and path.is_dir() and _is_inside_root(path):
        shutil.rmtree(path, ignore_errors=True)
        print(f"  removed dir: {path.relative_to(ROOT)}")


def _remove_file(path: Path) -> None:
    if path.exists() and path.is_file() and _is_inside_root(path):
        try:
            path.unlink()
            print(f"  removed file: {path.relative_to(ROOT)}")
        except OSError:
            pass


def main() -> int:
    print("[cleanup] removing generated packaging intermediates...")

    for rel in (
        "src/dist",
        "src/build",
        "src/build_mini",
        "build/output/config",
    ):
        _remove_dir(ROOT / rel)

    for pycache in ROOT.rglob("__pycache__"):
        _remove_dir(pycache)

    for pattern in ("*.pyc", "*.pyo", "*.spec"):
        for item in ROOT.rglob(pattern):
            _remove_file(item)

    print("[cleanup] done.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
