"""Enron dataset provider - uses same interface as Gmail/IMAP."""
import logging
from typing import List, Dict, Optional
from pathlib import Path

from .base import BaseProvider, Email
from src.calibration.enron_parser import EnronParser

logger = logging.getLogger(__name__)


class EnronProvider(BaseProvider):
    """
    Enron dataset provider.

    Uses the same Email data model and BaseProvider interface as Gmail/IMAP,
    ensuring test code paths are identical to production.
    """

    def __init__(self, maildir_path: str = "."):
        """
        Initialize Enron provider.

        Args:
            maildir_path: Path to directory containing maildir/ folder
        """
        self.parser = EnronParser(maildir_path)
        self.connected = False

    def connect(self, credentials: Dict = None) -> bool:
        """
        Connect to Enron dataset (no auth needed).

        Args:
            credentials: Not used for Enron dataset

        Returns:
            Always True for Enron
        """
        self.connected = True
        logger.info("Connected to Enron dataset")
        return True

    def fetch_emails(self, limit: int = None, filters: Dict = None) -> List[Email]:
        """
        Fetch emails from Enron dataset.

        Args:
            limit: Maximum number of emails to fetch
            filters: Optional filters (not implemented for Enron)

        Returns:
            List of Email objects
        """
        if not self.connected:
            logger.warning("Not connected to Enron dataset")
            return []

        logger.info(f"Fetching up to {limit or 'all'} emails from Enron dataset")
        emails = self.parser.parse_emails(limit=limit)
        logger.info(f"Fetched {len(emails)} emails")

        return emails

    def get_ground_truth_label(self, email: Email) -> str:
        """
        Extract ground truth category from email metadata.

        For Enron emails, the folder name is the ground truth label:
        - inbox -> conversational/work
        - sent -> conversational
        - deleted_items -> junk
        - etc.

        Args:
            email: Email object with metadata

        Returns:
            Folder name as ground truth category
        """
        # EnronParser should set this in metadata
        return email.headers.get('X-Folder', 'unknown')

    def update_labels(self, email_id: str, labels: List[str]) -> bool:
        """
        Update labels (not supported for Enron dataset).

        Args:
            email_id: Email ID
            labels: List of labels to add

        Returns:
            Always False for Enron
        """
        logger.warning("Label updates not supported for Enron dataset")
        return False

    def batch_update(self, updates: List[Dict]) -> bool:
        """
        Batch update (not supported for Enron dataset).

        Args:
            updates: List of update operations

        Returns:
            Always False for Enron
        """
        logger.warning("Batch updates not supported for Enron dataset")
        return False

    def disconnect(self):
        """Disconnect from Enron dataset."""
        self.connected = False
        logger.info("Disconnected from Enron dataset")
