"""Honeypot Collector — aggregates all tool call attempts from honeypot servers.

Stores interactions with full request details for offline analysis and
real-time pattern extraction.
"""

from __future__ import annotations

import json
import logging
import threading
from collections import deque
from datetime import datetime, timezone
from typing import Any

logger = logging.getLogger(__name__)


class HoneypotCollector:
    """Collects and stores honeypot interaction records.

    Thread-safe collector that accumulates records from one or more
    honeypot server instances.

    Usage::

        collector = HoneypotCollector(max_records=10000)
        server = HoneypotMCPServer(profile="dev_tools", collector=collector)
    """

    def __init__(self, max_records: int = 10000) -> None:
        self._records: deque[dict[str, Any]] = deque(maxlen=max_records)
        self._lock = threading.Lock()
        self._total_count: int = 0

    def record(self, honeypot_record: Any) -> None:
        """Record a honeypot interaction.

        Args:
            honeypot_record: A HoneypotRecord instance (from server.py).
        """
        entry = {
            "timestamp": honeypot_record.timestamp,
            "tool_name": honeypot_record.tool_name,
            "arguments": honeypot_record.arguments,
            "source_ip": honeypot_record.source_ip,
            "request_headers": honeypot_record.request_headers,
            "method": honeypot_record.method,
        }

        with self._lock:
            self._records.append(entry)
            self._total_count += 1

    @property
    def records(self) -> list[dict[str, Any]]:
        """Return a snapshot of all collected records."""
        with self._lock:
            return list(self._records)

    @property
    def count(self) -> int:
        """Total number of records collected (including evicted)."""
        return self._total_count

    @property
    def current_count(self) -> int:
        """Number of records currently in buffer."""
        with self._lock:
            return len(self._records)

    def get_records_since(self, since: str) -> list[dict[str, Any]]:
        """Get records collected after the given ISO timestamp.

        Args:
            since: ISO-format timestamp string.

        Returns:
            List of records with timestamp > since.
        """
        with self._lock:
            return [r for r in self._records if r["timestamp"] > since]

    def get_tool_call_counts(self) -> dict[str, int]:
        """Get per-tool call count summary."""
        counts: dict[str, int] = {}
        with self._lock:
            for r in self._records:
                tool = r["tool_name"]
                counts[tool] = counts.get(tool, 0) + 1
        return counts

    def get_source_ip_counts(self) -> dict[str, int]:
        """Get per-source-IP call count summary."""
        counts: dict[str, int] = {}
        with self._lock:
            for r in self._records:
                ip = r["source_ip"]
                counts[ip] = counts.get(ip, 0) + 1
        return counts

    def export_json(self) -> str:
        """Export all records as a JSON string."""
        return json.dumps(self.records, indent=2)

    def clear(self) -> int:
        """Clear all records. Returns the number of records cleared."""
        with self._lock:
            count = len(self._records)
            self._records.clear()
            return count
