import time
import requests
from requests import RequestException
from rich.console import Console

from .config import DEFAULT_RETRIES

console = Console()

class NetworkHelper:
    def __init__(self, console: Console = console, retries: int = DEFAULT_RETRIES):
        self.console = console
        self.retries = retries

    def request(self, func, spinner_text=None):
        last_exc = None
        for attempt in range(max(1, self.retries)):
            try:
                if spinner_text:
                    with self.console.status(f"[cyan]{spinner_text}[/cyan]", spinner="dots"):
                        r = func()
                else:
                    r = func()
                return r
            except RequestException as exc:
                last_exc = exc
                self.console.print(f"[yellow]Network error (attempt {attempt+1}/{self.retries}):[/yellow] {exc}")
                time.sleep(0.6 + attempt * 0.5)
        if last_exc:
            raise last_exc
        raise RuntimeError("NetworkHelper.request failed without exception")
