# apps/aroflo_connector_app/ui_automation_zones/maintenance/cleanup_artifacts.py
from __future__ import annotations

import time
from pathlib import Path
from typing import List, Union


def cleanup_artifacts(*, artifacts_dir: Path, days: int = 14, dry_run: bool = True) -> Union[int, List[Path]]:
    """
    Borra carpetas de corrida dentro de artifacts_dir más viejas que N días.
    Cada corrida es un folder tipo: timesheet-create-YYYYMMDD-HHMMSS.

    Retorna:
      - dry_run=True: lista de Path que se borrarían
      - dry_run=False: int con cantidad de carpetas borradas
    """
    artifacts_dir = Path(artifacts_dir)
    if not artifacts_dir.exists():
        return [] if dry_run else 0

    cutoff = time.time() - (days * 86400)
    candidates: List[Path] = []

    for p in artifacts_dir.iterdir():
        if not p.is_dir():
            continue
        try:
            st = p.stat()
            if st.st_mtime < cutoff:
                candidates.append(p)
        except Exception:
            continue

    if dry_run:
        for p in sorted(candidates):
            print(f"[UIZ][dry-run] would delete: {p}")
        return candidates

    deleted = 0
    for p in candidates:
        try:
            # borrar recursivo sin shutil.rmtree para no depender de permisos raros:
            for child in p.rglob("*"):
                try:
                    if child.is_file() or child.is_symlink():
                        child.unlink(missing_ok=True)
                except Exception:
                    pass
            # borrar dirs bottom-up
            for child in sorted(p.rglob("*"), reverse=True):
                try:
                    if child.is_dir():
                        child.rmdir()
                except Exception:
                    pass
            p.rmdir()
            deleted += 1
            print(f"[UIZ] deleted: {p}")
        except Exception:
            print(f"[UIZ] failed to delete: {p}")
            continue

    return deleted
