#!/usr/bin/env python3
"""
blue_team.py - Defensive Entropy Monitoring (Guardian)
=======================================================

Blue Team role: Monitor for entropy threshold breaches and fire alerts.
This is the defensive/guardian layer that watches for Red Team activity.

Consolidated from:
- receipts/.../ReflexRange01/blue_team/guardian_entropy_reflex.py

WO#NET_JAZZ_00
"""

from pathlib import Path
from collections import deque
from datetime import datetime
from typing import Optional, Callable, Dict, Any
import time


# Default entropy threshold (number of [ENTROPY] lines to trigger alert)
DEFAULT_ENTROPY_THRESHOLD = 800

# Alert tag
ENTROPY_ALERT_TAG = "::ENTROPY_ALERT::"


def check_entropy_threshold(
    log_path: Path,
    threshold: int = DEFAULT_ENTROPY_THRESHOLD,
    pattern: str = "[ENTROPY]"
) -> Dict[str, Any]:
    """
    Check if entropy count exceeds threshold.

    Args:
        log_path: Path to log file to monitor
        threshold: Number of entropy lines to trigger alert
        pattern: Pattern to match for entropy lines

    Returns:
        Dict with check results
    """
    if not log_path.exists():
        return {
            "checked": False,
            "count": 0,
            "threshold": threshold,
            "exceeded": False,
            "error": f"Log file not found: {log_path}",
        }

    count = 0
    recent_lines = deque(maxlen=100)

    with open(log_path, 'r', errors='ignore') as f:
        for line in f:
            if pattern in line:
                count += 1
                recent_lines.append(line.strip())

    return {
        "checked": True,
        "count": count,
        "threshold": threshold,
        "exceeded": count > threshold,
        "recent_lines": list(recent_lines),
        "log_path": str(log_path),
        "timestamp": datetime.now().isoformat(),
    }


def entropy_alert(
    log_path: Path,
    message: str = "Entropy threshold breached – reflex activated"
) -> None:
    """
    Write an entropy alert to the log.

    Args:
        log_path: Path to log file
        message: Alert message
    """
    log_path.parent.mkdir(parents=True, exist_ok=True)
    timestamp = datetime.now().isoformat()
    with open(log_path, 'a') as f:
        f.write(f"[{timestamp}] {ENTROPY_ALERT_TAG} {message}\n")


def monitor_entropy(
    log_path: Path,
    threshold: int = DEFAULT_ENTROPY_THRESHOLD,
    on_alert: Optional[Callable[[Dict[str, Any]], None]] = None,
    continuous: bool = False,
    poll_interval: float = 1.0
) -> Dict[str, Any]:
    """
    Monitor log for entropy threshold breach.

    Args:
        log_path: Path to log file to monitor
        threshold: Entropy count threshold
        on_alert: Callback when threshold exceeded
        continuous: If True, poll continuously (blocking)
        poll_interval: Seconds between polls in continuous mode

    Returns:
        Dict with final check results
    """
    while True:
        result = check_entropy_threshold(log_path, threshold=threshold)

        if result["exceeded"]:
            # Fire alert
            entropy_alert(log_path, f"Entropy count {result['count']} exceeds threshold {threshold}")

            if on_alert:
                on_alert(result)

            result["alert_fired"] = True

            if not continuous:
                return result

        if not continuous:
            result["alert_fired"] = False
            return result

        time.sleep(poll_interval)


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

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

    parser = argparse.ArgumentParser(description="Blue Team Entropy Guardian")
    parser.add_argument("--log", type=Path, default=Path("/tmp/reflex_test.log"),
                        help="Log file to monitor")
    parser.add_argument("--threshold", type=int, default=800,
                        help="Entropy threshold")
    parser.add_argument("--continuous", action="store_true",
                        help="Run continuous monitoring")
    parser.add_argument("--poll", type=float, default=1.0,
                        help="Poll interval in seconds")
    args = parser.parse_args()

    print(f"[BLUE_TEAM] Monitoring: {args.log}")
    print(f"[BLUE_TEAM] Threshold: {args.threshold}")

    def on_alert(result):
        print(f"[BLUE_TEAM] ALERT! Entropy count: {result['count']}")

    result = monitor_entropy(
        args.log,
        threshold=args.threshold,
        on_alert=on_alert,
        continuous=args.continuous,
        poll_interval=args.poll
    )

    print(f"[BLUE_TEAM] Check result: exceeded={result['exceeded']}, count={result['count']}")


if __name__ == "__main__":
    _cli()
