# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# Licensed under the MIT License

"""
Email Intelligence Suggestions — proactive recommendations
based on engagement data and classification patterns.

Generates actionable suggestions like:
- "You never open emails from X — mark as Promotional?"
- "You reply to Y frequently — add as VIP?"
- "12 senders have List-Unsubscribe and you never open them"
"""

import logging
from datetime import datetime

logger = logging.getLogger(__name__)


def generate_suggestions(limit: int = 5) -> list:
    """Generate proactive email intelligence suggestions.

    Returns list of {type, title, description, action, action_data}
    """
    suggestions = []

    # 1. High-engagement senders not VIP
    try:
        from familiar.skills.email.engagement import get_top_engaged
        from familiar.skills.triage.skill import _load_triage_data

        triage = _load_triage_data()
        vips = set(s.lower() for s in triage.get("vip_senders", []))
        top = get_top_engaged(limit=20)

        for s in top:
            sender = s.get("sender", "").lower()
            if sender and sender not in vips and s.get("engagement_score", 0) > 1.5:
                replies = s.get("replied", 0)
                opens = s.get("opened", 0)
                total = s.get("total_received", 0)
                suggestions.append({
                    "type": "add_vip",
                    "title": f"Add {sender} as VIP?",
                    "description": f"You've replied {replies}x and opened {opens}/{total} emails from this sender.",
                    "action": "add_vip",
                    "action_data": {"sender": sender},
                })
    except Exception as e:
        logger.debug("VIP suggestions failed: %s", e)

    # 2. Low-engagement senders to mark Promotional
    try:
        from familiar.skills.email.engagement import get_low_engaged

        low = get_low_engaged(min_received=5, limit=20)
        if low:
            # Group by domain for cleaner suggestions
            domains = {}
            for s in low:
                sender = s.get("sender", "")
                domain = sender.split("@")[-1] if "@" in sender else sender
                if domain not in domains:
                    domains[domain] = []
                domains[domain].append(s)

            for domain, senders in sorted(domains.items(), key=lambda x: -len(x[1])):
                total_received = sum(s.get("total_received", 0) for s in senders)
                total_opened = sum(s.get("opened", 0) for s in senders)
                if total_received >= 5 and total_opened == 0:
                    count = len(senders)
                    suggestions.append({
                        "type": "mark_promotional",
                        "title": f"Mark @{domain} as Promotional?",
                        "description": f"{count} sender{'s' if count > 1 else ''}, {total_received} emails received, never opened.",
                        "action": "mark_domain_promotional",
                        "action_data": {"domain": domain},
                    })
    except Exception as e:
        logger.debug("Promotional suggestions failed: %s", e)

    # 3. Model training suggestion
    try:
        from familiar.skills.email.training_data import get_stats
        from familiar.skills.email.model import get_model_info

        td = get_stats()
        mi = get_model_info()
        if td.get("ready_for_model") and not mi.get("trained"):
            suggestions.append({
                "type": "train_model",
                "title": "Train your email classifier",
                "description": f"{td['total_pairs']} training pairs available. Train the model to improve accuracy.",
                "action": "train_model",
                "action_data": {},
            })
        elif mi.get("trained") and td.get("total_pairs", 0) > mi.get("docs", 0) + 20:
            suggestions.append({
                "type": "retrain_model",
                "title": "Retrain model with new data",
                "description": f"{td['total_pairs'] - mi['docs']} new training pairs since last train. Accuracy may improve.",
                "action": "train_model",
                "action_data": {},
            })
    except Exception:
        pass

    # 4. Google Contacts sync suggestion
    try:
        from pathlib import Path

        data_dir = Path.home() / ".familiar" / "data"
        has_token = (data_dir / "google_token_contacts.json").exists()
        has_contacts = (data_dir / "contacts.json").exists()
        if has_token and not has_contacts:
            suggestions.append({
                "type": "sync_contacts",
                "title": "Sync Google Contacts",
                "description": "Import your contacts to auto-prioritize emails from people you know.",
                "action": "sync_contacts",
                "action_data": {},
            })
    except Exception:
        pass

    return suggestions[:limit]
