import shutil
from logging.handlers import RotatingFileHandler
from rich.console import Console
from rich.logging import RichHandler
import sys

class MyRichHandler(RichHandler):
    def __init__(self, file="stdout", **kwargs):
        super().__init__(**kwargs)
        if file not in ("stdout", "stderr"):
            raise ValueError("file must be 'stdout' or 'stderr'")
        self.console = Console(file=getattr(sys, file))


class SafeRotatingFileHandler(RotatingFileHandler):
    """Evita erro de PermissionError no Windows ao fazer rollover."""

    def rotate(self, source, dest):
        try:
            super().rotate(source, dest)
        except PermissionError:
            shutil.copy2(source, dest)
            with open(source, "w", encoding="utf-8") as f:
                f.truncate(0)
