"""Autopilot mode: auto-approve, batch notifications, digest generation."""

from __future__ import annotations

import logging
from datetime import UTC, datetime

log = logging.getLogger(__name__)


class AutopilotService:
    """Manages autopilot mode: auto-approvals, notification batching, digest."""

    def __init__(self) -> None:
        self._enabled = False
        self._expires: str | None = None
        self._notification_queue: list[dict] = []

    @property
    def is_enabled(self) -> bool:
        """Check if autopilot is active (respects expiry)."""
        if not self._enabled:
            return False
        if self._expires:
            now = datetime.now(UTC).isoformat()
            if now > self._expires:
                self._enabled = False
                log.info("Autopilot auto-disabled (expired)")
                return False
        return True

    def enable(self, until: str | None = None) -> None:
        """Enable autopilot, optionally with an expiry date (YYYY-MM-DD)."""
        self._enabled = True
        if until:
            self._expires = f"{until}T23:59:59"
        else:
            self._expires = None
        log.info("Autopilot enabled (expires: %s)", self._expires or "never")

    def disable(self) -> dict:
        """Disable autopilot and return a welcome-back summary."""
        self._enabled = False
        queued = len(self._notification_queue)
        notifications = list(self._notification_queue)
        self._notification_queue.clear()
        log.info("Autopilot disabled. %d queued notifications.", queued)
        return {
            "queued_notifications": queued,
            "notifications": notifications,
        }

    def queue_notification(self, text: str, channel: str = "web") -> None:
        """Queue a notification for the daily digest instead of sending immediately."""
        if self.is_enabled:
            self._notification_queue.append({
                "text": text,
                "channel": channel,
                "timestamp": datetime.now(UTC).isoformat(),
            })
        # If not in autopilot, notifications should be sent immediately by the caller

    def get_digest(self) -> list[dict]:
        """Get the current notification queue as a digest."""
        return list(self._notification_queue)

    def clear_digest(self) -> int:
        """Clear the notification queue. Returns count cleared."""
        count = len(self._notification_queue)
        self._notification_queue.clear()
        return count

    def should_auto_approve(self, domain: str, trust_level: str) -> bool:
        """Check if an action should be auto-approved in autopilot mode.

        In autopilot: tasks in trusted domains (trust >= Assistant) auto-approve.
        """
        if not self.is_enabled:
            return False
        return trust_level in ("Assistant", "Partner")

    def status(self) -> dict:
        """Get autopilot status."""
        return {
            "enabled": self.is_enabled,
            "expires": self._expires,
            "queued_notifications": len(self._notification_queue),
        }
