"""
Stress Testing Harness

Submits high volume of intents to test system stability and performance.
"""

import threading
import time
import uuid
import random
from typing import List, Dict, Optional
from altrus.core.intent.intent import Intent, IntentPriority

class StressTester:
    """
    Mocks a high-load environment by submitting many intents.
    """

    def __init__(self, kernel):
        self.kernel = kernel
        self._running = False
        self._threads: List[threading.Thread] = []
        self.stats = {
            "submitted": 0,
            "failed": 0,
            "last_latency": 0.0
        }

    def start(self, workers: int = 5, intensity: float = 1.0):
        """
        Start stress test.

        Args:
            workers: Number of concurrent submitters
            intensity: Sleep time between submissions (smaller = higher load)
        """
        self._running = True
        for i in range(workers):
            t = threading.Thread(target=self._worker_loop, args=(intensity,), daemon=True)
            t.start()
            self._threads.append(t)
        print(f"🏋️ Stress Test started with {workers} workers (intensity={intensity})")

    def stop(self):
        """Stop stress test"""
        self._running = False
        for t in self._threads:
            t.join(timeout=1.0)
        print("🏋️ Stress Test stopped")

    def _worker_loop(self, intensity: float):
        capabilities = ["nav.move", "tele.call", "sensor.scan"]

        while self._running:
            time.sleep(intensity + random.random() * 0.5)

            intent = Intent(
                intent_id=f"stress_{uuid.uuid4().hex[:8]}",
                name=f"Stress Task {self.stats['submitted']}",
                capability=random.choice(capabilities),
                priority=random.choice(list(IntentPriority)),
                ttl=60
            )

            start_time = time.time()
            try:
                self.kernel.intent_engine.submit_intent(intent)
                self.stats["submitted"] += 1
                self.stats["last_latency"] = time.time() - start_time
            except Exception as e:
                print(f"❌ Stress test submission failed: {e}")
                self.stats["failed"] += 1

    def get_report(self) -> Dict:
        """Get current performance stats"""
        return {
            "submitted_total": self.stats["submitted"],
            "failed_total": self.stats["failed"],
            "avg_submission_latency_ms": self.stats["last_latency"] * 1000,
            "active_intents": len(self.kernel.intent_engine.list_intents())
        }
