#!/usr/bin/env python3
"""
red_team.py - Adversarial Entropy Injection
============================================

Red Team role: Stress-test the system by injecting entropy.
Used for testing Blue Team's monitoring and Purple Team's orchestration.

Consolidated from:
- receipts/.../ReflexRange01/red_team/run_entropy_bleed.py

WO#NET_JAZZ_00
"""

import random
import string
import time
from pathlib import Path
from typing import Optional, Callable
from datetime import datetime


def generate_entropy_line(length: int = 128) -> str:
    """
    Generate a random entropy line.

    Args:
        length: Length of random string

    Returns:
        Random alphanumeric string
    """
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))


def inject_entropy(
    log_path: Path,
    tag: str = "ENTROPY",
    count: int = 1,
    delay: float = 0.0
) -> int:
    """
    Inject entropy lines into a log file.

    Args:
        log_path: Path to the log file
        tag: Tag to use for entropy lines (e.g., "ENTROPY", "RED_INJECT")
        count: Number of lines to inject
        delay: Delay between injections (seconds)

    Returns:
        Number of lines injected
    """
    log_path.parent.mkdir(parents=True, exist_ok=True)

    injected = 0
    for _ in range(count):
        line = generate_entropy_line()
        timestamp = datetime.now().isoformat()
        with open(log_path, 'a') as f:
            f.write(f"[{timestamp}] [{tag}] {line}\n")
        injected += 1
        if delay > 0 and injected < count:
            time.sleep(delay)

    return injected


def entropy_flood(
    log_path: Path,
    count: int = 1000,
    delay: float = 0.01,
    on_inject: Optional[Callable[[int], None]] = None
) -> dict:
    """
    Flood a log file with entropy (stress test).

    This is the "adversarial" Red Team function that intentionally
    pushes the Blue Team's monitoring threshold.

    Args:
        log_path: Path to target log file
        count: Number of entropy lines to inject
        delay: Delay between injections
        on_inject: Optional callback with current count

    Returns:
        Dict with injection stats
    """
    start_time = time.time()

    for i in range(count):
        inject_entropy(log_path, tag="ENTROPY", count=1, delay=0)
        if on_inject:
            on_inject(i + 1)
        if delay > 0:
            time.sleep(delay)

    elapsed = time.time() - start_time

    return {
        "injected": count,
        "elapsed_seconds": elapsed,
        "rate_per_second": count / elapsed if elapsed > 0 else 0,
        "log_path": str(log_path),
        "timestamp": datetime.now().isoformat(),
    }


# ============================================================================
# CLI
# ============================================================================

def _cli():
    """Red Team CLI."""
    import argparse

    parser = argparse.ArgumentParser(description="Red Team Entropy Injector")
    parser.add_argument("--log", type=Path, default=Path("/tmp/reflex_test.log"),
                        help="Target log file")
    parser.add_argument("--count", type=int, default=100,
                        help="Number of lines to inject")
    parser.add_argument("--delay", type=float, default=0.01,
                        help="Delay between injections")
    parser.add_argument("--flood", action="store_true",
                        help="Run flood mode (stress test)")
    args = parser.parse_args()

    print(f"[RED_TEAM] Injecting entropy to: {args.log}")

    if args.flood:
        result = entropy_flood(args.log, count=args.count, delay=args.delay)
        print(f"[RED_TEAM] Flood complete: {result['injected']} lines in {result['elapsed_seconds']:.2f}s")
    else:
        injected = inject_entropy(args.log, count=args.count, delay=args.delay)
        print(f"[RED_TEAM] Injected {injected} entropy lines")


if __name__ == "__main__":
    _cli()
