Metadata-Version: 2.4
Name: nano_wait
Version: 4.0.3
Summary: Adaptive waiting and execution engine — replaces time.sleep() with system-aware, deterministic waiting.
Author: Luiz Filipe Seabra de Marco
Author-email: luizfilipeseabra@icloud.com
License: MIT
Keywords: automation,adaptive wait,smart wait,execution engine,system-aware,deterministic automation,rpa core,testing,performance,psutil,wifi awareness,system context,sleep replacement
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Utilities
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: psutil
Requires-Dist: pywifi
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-mock; extra == "dev"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# NanoWait: The Adaptive Wait Engine for Python

[![PyPI version](https://img.shields.io/pypi/v/nano_wait.svg)](https://pypi.org/project/nano_wait/)
[![License](https://img.shields.io/pypi/l/nano_wait.svg)](https://github.com/luizfilipe/NanoWait/blob/main/LICENSE)
[![Python Version](https://img.shields.io/pypi/pyversions/nano_wait.svg)](https://pypi.org/project/nano_wait/)

## 🚀 What is NanoWait?

**NanoWait** is a deterministic and adaptive execution wait engine designed to replace Python's standard `time.sleep()`. Instead of waiting for a fixed duration, NanoWait dynamically adjusts the wait time based on **system load (CPU/RAM)** and, optionally, **Wi-Fi signal strength**, ensuring automation scripts remain reliable even in slow or overloaded environments.

With the introduction of **Execution Profiles**, NanoWait now offers a semantic layer to manage wait behavior, allowing you to define the operational context clearly and consistently.

> **In summary:** you request a base time (e.g., `wait(5)`), and NanoWait ensures a *safe and context-aware wait* that never exceeds the requested time and never falls below a minimum execution floor.

---

## 🛠️ Installation

```bash
pip install nano_wait
```

### Optional Module — Vision Mode

Visual waiting (icon/state detection) has been intentionally moved to a dedicated package to keep NanoWait lightweight and deterministic.

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

If Vision Mode is not installed, NanoWait will raise a clear runtime error when visual functionalities are requested.

---

## 💡 Quick Guide

```python
from nano_wait import wait
import time

# Standard sleep
start = time.time()
time.sleep(5)
print(f"time.sleep(): {time.time() - start:.2f}s")

# Adaptive wait
start = time.time()
wait(5)
print(f"nano_wait.wait(): {time.time() - start:.2f}s")
```

NanoWait **never waits longer than the requested base time** and applies a minimum internal delay of **50 ms** to prevent excessive CPU usage.

---

## ⚙️ Core API

```python
wait(
    t: float | None = None,
    *,
    wifi: str | None = None,
    speed: str | float = "normal",
    smart: bool = False,
    explain: bool = False,
    verbose: bool = False,
    log: bool = False,
    profile: str | None = None
) -> float | ExplainReport
```

### Parameters

| Parameter | Description                                                                 |
|-----------|---------------------------------------------------------------------------|
| `t`       | Base time in seconds (required for time-based waiting).                   |
| `wifi`    | Wi-Fi network SSID to assess signal quality (optional).                   |
| `speed`   | Execution speed preset or numeric value.                                  |
| `smart`   | Activates Smart Context Mode (dynamic speed calculation).                 |
| `explain` | Activates Explain Mode, which returns a detailed decision report.         |
| `verbose` | Prints debug information to `stdout`.                                     |
| `log`     | Writes execution data to `nano_wait.log`.                                 |
| `profile` | Selects a predefined execution profile (e.g., "ci", "rpa").             |

---

## 🧩 Execution Profiles (New Feature)

Execution Profiles introduce a semantic layer over NanoWait's adaptive wait engine. Instead of manually adjusting isolated parameters (speed, aggressiveness, verbosity), you can select an execution profile that represents the operational context in which your code is running — such as continuous integration (CI), automated tests, or robotic process automation (RPA).

Each profile encapsulates a coherent set of decisions, ensuring consistency, readability, and reduced cognitive complexity for the user.

### 🎯 Why use Execution Profiles?

Without profiles, scripts tend to accumulate fragile adjustments:

```python
wait(2, speed="fast", smart=True, verbose=True)
```

With Execution Profiles, the focus shifts to the environment, not mechanical details:

```python
wait(2, profile="ci")
```

### ⚙️ How to use

Basic usage:

```python
from nano_wait import wait

# Executes the wait using the Continuous Integration profile
wait(2, profile="ci")
```

If no profile is specified, NanoWait uses the default profile.

### 🧪 Available Profiles

| Profile   | Recommended Use                      | General Behavior                        |
|-----------|--------------------------------------|-----------------------------------------|
| `ci`      | CI/CD Pipelines                      | Aggressive waits, verbose enabled       |
| `testing` | Local Automated Tests                | Balance between speed and stability     |
| `rpa`     | Interface and Human Workflow Automation | More conservative waits                 |
| `default` | Generic Execution                    | Balanced behavior                       |

### 🧠 What does an Execution Profile control?

Internally, each profile defines:

*   Aggressiveness of time adaptation
*   Tolerance to transient instabilities
*   Polling interval
*   Default verbosity (automatic debug)

These parameters are applied deterministically to each execution.

### 🔄 Integration with Smart Context Mode

Execution Profiles do not replace Smart Context Mode — they complement each other.

```python
wait(
    t=3,
    smart=True,
    profile="testing"
)
```

In this example:

*   Smart Mode calculates the optimal speed based on the system
*   The Execution Profile adjusts the overall wait behavior

### 🧪 Comparative Example

Without Execution Profiles:

```python
wait(
    t=2,
    speed="fast",
    smart=True,
    verbose=True
)
```

With Execution Profiles:

```python
wait(
    t=2,
    profile="ci"
)
```

The second example is more readable, more consistent, and less fragile to future changes.

### 🖥️ Command Line Interface (CLI)

Execution Profiles are also available in the CLI:

```bash
nano-wait 2 --profile ci
```

With Explain Mode:

```bash
nano-wait 2 --profile testing --explain
```

### 🔍 Execution Profiles in Explain Mode

When Explain Mode is active, the applied profile implicitly appears in the final wait behavior:

```python
report = wait(
    t=1.5,
    profile="rpa",
    explain=True
)

print(report.explain())
```

Example output:

```
Requested time: 1.5s
Final wait time: 1.32s
Speed input: normal → 1.5
Smart mode: False
CPU score: 6.1
Adaptive factor: 1.08
Execution profile: rpa
```

### 🧠 Design Philosophy

Execution Profiles reflect a core principle of NanoWait:

> Code should express intent, not mechanical adjustments.

By moving time and tolerance decisions to semantic profiles, NanoWait promotes more robust, predictable, and maintainable APIs — especially in complex automated systems.

---

## 🔬 Explain Mode (`explain=True`)

Explain Mode makes NanoWait's waiting mechanism deterministic, auditable, and explainable. It does not alter the wait behavior but **reveals how the decision was made**.

When activated, `wait()` returns a dictionary (`Explain Report`) with all factors used in the calculation, ideal for debugging, auditing, and benchmarking.

### Code Example

```python
from nano_wait import wait

report = wait(
    t=1.5,
    speed="fast",
    smart=True,
    explain=True
)

print(report)
```

**Report Structure:**

```json
{
  "requested_speed": "fast",
  "speed_value": 0.5,
  "adaptive_factor": 1.39,
  "base_seconds": 0.5,
  "adjusted_seconds": 0.695,
  "floor_applied": true,
  "final_seconds": 0.7,
  "profile": "fast",
  "system_load": 0.62
}

```

---

## 🧠 Smart Context Mode (`smart=True`)

When activated, NanoWait automatically calculates the execution speed based on the **average system context score**.

```python
wait(10, smart=True, verbose=True)
```

Example output:

```
[NanoWait] speed=3.42 factor=2.05 wait=4.878s
```

### How Smart Speed Works

*   **PC Score** → derived from CPU and memory usage.
*   **Wi-Fi Score** → derived from RSSI (if activated).

The final **Smart Speed** is:

```
speed = clamp( (pc_score + wifi_score) / 2 , 0.5 , 5.0 )
```

This value is used directly as the execution speed factor.

---

## 🌐 Wi-Fi Awareness

If your automation depends on network stability, NanoWait can adapt its waiting behavior based on Wi-Fi signal strength.

```python
wait(5, wifi="MyNetwork_5G")
```

Supported platforms:

*   Windows (`pywifi`)
*   macOS (`airport`)
*   Linux (`nmcli`)

If Wi-Fi data cannot be read, NanoWait safely defaults to neutral values.

---

## ⚡ Execution Speed Presets

NanoWait supports symbolic speed presets, as well as numeric values.

| Preset       | Internal Value |
|--------------|----------------|
| `slow`       | 0.8            |
| `normal`     | 1.5            |
| `fast`       | 3.0            |
| `ultra`      | 6.0            |

```python
wait(2, speed="fast")
wait(2, speed=2.2)
```

Higher speeds reduce the nominal wait time more aggressively.

---

## 🖥️ Command Line Interface (CLI)

NanoWait can be executed directly from the terminal:

```bash
nano-wait <time> [options]
```

**Example:**

```bash
nano-wait 5 --smart --verbose
```

**New in CLI: `--explain` and `--profile`**

Use the `--explain` and `--profile` flags to get the explanation report and apply profiles directly in the terminal.

```bash
python -m nano_wait.cli 1.5 --speed fast --explain --profile ci
```

**Expected Output:**

```
--- NanoWait Explain Report ---
Requested time: 1.5s
Final wait time: 1.079s
Speed input: fast → 3.0
Smart mode: False
CPU score: 5.83
Adaptive factor: 1.39
Minimum floor applied: False
Maximum cap applied: False
Timestamp: 2026-01-06T23:59:25
Execution profile: ci
```

**Available Flags:**

*   `--wifi SSID`
*   `--speed slow|normal|fast|ultra`
*   `--smart`
*   `--explain`
*   `--verbose`
*   `--log`
*   `--profile ci|testing|rpa|default`

---

## 👁️ Visual Waiting (Optional)

Visual waiting functionalities (icons, UI states) are loaded on demand and require:

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

If not installed, NanoWait raises a clear `ImportError` explaining how to enable the functionality.

---

## 🧪 Design Guarantees

*   Deterministic behavior
*   No busy-waiting
*   Safe fallback paths
*   Cross-platform support
*   Production-ready API

---

## 🤝 Contribution and License

NanoWait is open-source and licensed under the MIT License. Your contribution is highly welcome!

We encourage the community to interact and collaborate. If you find a bug, have a suggestion for improvement, or want to discuss new features, please use GitHub:

*   **Report an issue (Issues):** [https://github.com/luizfilipe/NanoWait/issues](https://github.com/LuizSeabraDeMarco/NanoWait/issues)
*   **Discussions:** [https://github.com/luizfilipe/NanoWait/discussions](https://github.com/LuizSeabraDeMarco/NanoWait/discussions)

**Author:** Luiz Filipe Seabra de Marco
**License:** MIT
