# 🚀 NanoWait — Execution Layer for Python

**NanoWait is not a sleep function.
It’s an adaptive execution engine.**

> Execute. Retry. Adapt. Learn.

---

# 📦 Instalação

```bash
pip install nano-wait
```

---

# ⚡ Quick Start

## 1. Smart Wait (clássico, mas melhor)

```python
from nano_wait import wait

wait(2)  # adaptativo baseado no seu PC/Wi-Fi
```

---

## 2. Esperar até algo acontecer

```python
wait(lambda: button_is_visible(), timeout=10)
```

---

## 3. Execution Layer (🔥 principal)

```python
from nano_wait import execute

result = execute(lambda: fetch_data())

print(result)
```

---

## 4. Retry automático

```python
from nano_wait import retry

@retry(timeout=5)
def click_button():
    return driver.click("#submit")
```

---

# 🧠 Core Concepts

## 1. Adaptive Wait

NanoWait ajusta automaticamente o tempo com base em:

* CPU usage
* Memory usage
* Wi-Fi signal
* Execution profile
* Histórico (learning)

---

## 2. Execution Engine

O NanoWait não só espera — ele **executa com inteligência**:

```python
execute(
    fn,
    until=lambda result: result == "OK",
    timeout=10,
    interval=0.2
)
```

---

## 3. Scheduler

Internamente:

```python
schedule(interval)
```

→ substitui `time.sleep()` com inteligência adaptativa.

---

# 🔁 API Reference

---

## `wait()`

### Assinatura

```python
wait(
    t: float | Callable | None,
    timeout: float = 15.0,
    wifi: str | None = None,
    speed: str | float = "normal",
    smart: bool = False,
    verbose: bool = False,
    log: bool = False,
    explain: bool = False,
    telemetry: bool = False,
    profile: str | None = None
)
```

---

### Modos

#### ⏱ Time Mode

```python
wait(2)
```

#### 🔄 Condition Mode

```python
wait(lambda: is_ready(), timeout=10)
```

---

## `execute()` ⭐ (MAIN FEATURE)

```python
execute(
    fn: Callable,
    until: Callable | None = None,
    retry: bool = True,
    timeout: float = 10.0,
    interval: float = 0.1,
    **kwargs
)
```

---

### Exemplo real

```python
def fetch():
    return api.get_data()

result = execute(
    fetch,
    until=lambda r: r.status == 200,
    timeout=5
)
```

---

### Retorno

```python
ExecutionResult(
    success=True,
    result=...,
    attempts=3,
    duration=1.23
)
```

---

## `retry` decorator

```python
@retry(timeout=5, interval=0.2)
def connect():
    return connect_to_server()
```

---

# ⚙️ Perfis de Execução

```python
profile="ci"       # rápido e agressivo
profile="testing"  # balanceado
profile="rpa"      # mais estável
```

---

# 🧠 Smart Mode

```python
wait(2, smart=True)
```

Ajusta automaticamente baseado no ambiente:

* PC lento → espera mais
* PC rápido → espera menos

---

# 📊 Telemetry (Debug visual)

```python
wait(2, telemetry=True)
```

Mostra:

* Adaptive factor
* Intervalos
* Ajustes em tempo real

---

# 🧪 Explain Mode

```python
report = wait(2, explain=True)
print(report)
```

Retorna:

* tempo final
* fator usado
* CPU/Wi-Fi score
* decisões internas

---

# 🤖 CLI

## Wait normal

```bash
nano-wait 2
```

---

## Async

```bash
nano-wait 2 --async
```

---

## Pool

```bash
nano-wait --pool 1 2 3
```

---

## Auto

```bash
nano-wait --auto
```

---

## 🔥 Execution via CLI

```bash
nano-wait --exec "lambda: 1+1"
```

---

# 🧩 Exemplos Reais

---

## Selenium / Playwright

```python
execute(
    lambda: driver.find_element("#btn").click(),
    retry=True,
    timeout=5
)
```

---

## API Retry

```python
execute(
    lambda: requests.get(url),
    until=lambda r: r.status_code == 200
)
```

---

## RPA

```python
@retry(timeout=10)
def open_app():
    click_icon()
```

---

# 🧠 Learning Engine

NanoWait aprende automaticamente:

* Se demorou mais que o esperado
* Se houve timeout
* Ajusta futuras execuções

Arquivo salvo em:

```bash
~/.nano_wait_learning.json
```

---

# 🔥 Diferencial

NanoWait combina:

* `time.sleep()` ❌
* retry ❌
* polling ❌

em um único sistema:

✅ Adaptive Scheduler
✅ Execution Engine
✅ Self-learning
✅ Telemetry

---

# 🚀 Roadmap

* [ ] `execute_async`
* [ ] circuit breaker
* [ ] error classification
* [ ] integração com visão computacional (NanoWait Vision)

---

# 💡 Filosofia

> “Don’t wait blindly.
> Execute intelligently.”