"""Microsoft Defender process collector for OpenClaw detection."""

import json
import logging
from datetime import datetime, timedelta, timezone

from ..client import DefenderClient
from ..constants import RESULT_LIMIT

logger = logging.getLogger(__name__)

# Detection query - returns raw events, aggregation and filtering done in Python.
# Schema references:
#   DeviceProcessEvents: https://learn.microsoft.com/en-us/defender-xdr/advanced-hunting-deviceprocessevents-table
#   DeviceFileEvents:    https://learn.microsoft.com/en-us/defender-xdr/advanced-hunting-devicefileevents-table
PROCESS_QUERY = """
DeviceProcessEvents
| where Timestamp > _startTime
| where FolderPath matches regex @"(?i)(openclaw|clawdbot|clawbot|moltbot|\\.openclaw|\\.clawdbot|\\.moltbot)"
    or FileName matches regex @"(?i)(openclaw|clawdbot|clawbot|moltbot)"
    or ProcessCommandLine matches regex @"(?i)(openclaw|clawdbot|clawbot|moltbot)"
| project Timestamp, DeviceId, DeviceName, AccountName, FolderPath, FileName, ProcessCommandLine, EventType = "Process"
| join kind=leftouter (
    DeviceInfo
    | where Timestamp > _startTime
    | summarize arg_max(Timestamp, OSPlatform) by DeviceId
    | project DeviceId, osType = OSPlatform
) on DeviceId
| project Timestamp, DeviceName, AccountName, osType, FolderPath, FileName, ProcessCommandLine, EventType
"""


class DefenderProcessCollector:
    """Collector for OpenClaw detection via Microsoft Defender."""

    def __init__(self, client: DefenderClient, days_back: int):
        self.client = client
        self.days_back = days_back

    def _build_query(self) -> str:
        """Build query with time variable."""
        start = datetime.now(timezone.utc) - timedelta(days=self.days_back)
        start_str = start.strftime("%Y-%m-%dT%H:%M:%SZ")
        return f"let _startTime = datetime({start_str});\n{PROCESS_QUERY}"

    def collect_events(self) -> list[str]:
        """Execute query and return events."""
        query = self._build_query()
        logger.info(f"Executing Defender query (days_back={self.days_back})")

        events: list[str] = []
        for event in self.client.query(query):
            events.append(json.dumps(event))

        logger.info(f"Collected {len(events)} events from Defender")
        if len(events) >= RESULT_LIMIT:
            logger.warning(
                f"Collected {len(events)} events (API limit: {RESULT_LIMIT}). "
                "Results may be truncated -- consider reducing --days-back."
            )
        return events

    def run(self) -> list[str]:
        """Run collection and return events."""
        events = self.collect_events()
        logger.info("Process collection complete")
        return events
