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

"""
Email Intelligence Weekly Digest.

Generates a summary of email intelligence performance:
- Emails sorted, categories breakdown
- Training data growth
- Model accuracy
- Engagement trends
- Suggestions summary
"""

import logging
from datetime import datetime

logger = logging.getLogger(__name__)


def generate_digest() -> dict:
    """Generate the weekly email intelligence digest.

    Returns structured data for rendering in the briefing panel.
    """
    digest = {
        "generated_at": datetime.now().isoformat(),
        "sorting": {},
        "training": {},
        "model": {},
        "engagement": {},
        "suggestions": [],
    }

    # Sorting stats from cache
    try:
        from familiar.skills.email.monitor import get_sorted_inbox

        cache = get_sorted_inbox()
        summary = cache.get("summary", {})
        emails = cache.get("emails", [])

        # Category breakdown
        cats = {}
        for em in emails:
            c = em.get("category", "Other")
            cats[c] = cats.get(c, 0) + 1

        digest["sorting"] = {
            "total": summary.get("total", len(emails)),
            "urgent": summary.get("urgent", 0),
            "action": summary.get("action", 0),
            "fyi": summary.get("fyi", 0),
            "categories": cats,
        }
    except Exception as e:
        logger.debug("Digest sorting stats failed: %s", e)

    # Training data stats
    try:
        from familiar.skills.email.training_data import get_stats

        digest["training"] = get_stats()
    except Exception:
        pass

    # Model info
    try:
        from familiar.skills.email.model import get_model_info

        digest["model"] = get_model_info()
    except Exception:
        pass

    # Engagement stats
    try:
        from familiar.skills.email.engagement import get_stats as eng_stats

        digest["engagement"] = eng_stats()
    except Exception:
        pass

    # Top suggestions
    try:
        from familiar.skills.email.suggestions import generate_suggestions

        digest["suggestions"] = generate_suggestions(limit=3)
    except Exception:
        pass

    return digest


def format_digest_text(digest: dict) -> str:
    """Format digest as readable text for briefing/chat."""
    lines = ["\U0001f4ca **Email Intelligence Weekly Digest**\n"]

    s = digest.get("sorting", {})
    if s.get("total"):
        lines.append(f"**Sorted:** {s['total']} emails")
        cats = s.get("categories", {})
        if cats:
            cat_parts = [f"{cat}: {count}" for cat, count in sorted(cats.items(), key=lambda x: -x[1])]
            lines.append(f"  Categories: {', '.join(cat_parts)}")
        if s.get("urgent"):
            lines.append(f"  \U0001f534 {s['urgent']} urgent")
        if s.get("action"):
            lines.append(f"  \U0001f7e1 {s['action']} action")

    t = digest.get("training", {})
    if t.get("total_pairs"):
        lines.append(f"\n**Training:** {t['total_pairs']} pairs ({t.get('confirmed',0)} confirmed, {t.get('corrected',0)} corrected)")
        correction_rate = t.get("corrected", 0) / max(t.get("total_pairs", 1), 1)
        accuracy = round((1 - correction_rate) * 100)
        lines.append(f"  Estimated accuracy: {accuracy}%")

    m = digest.get("model", {})
    if m.get("trained"):
        lines.append(f"\n**Model:** Trained on {m['docs']} docs, {m.get('accuracy', 0):.0%} holdout accuracy")

    e = digest.get("engagement", {})
    if e.get("total_senders"):
        lines.append(f"\n**Engagement:** {e['total_senders']} senders tracked ({e.get('high',0)} high, {e.get('medium',0)} medium, {e.get('low',0)} low)")

    sug = digest.get("suggestions", [])
    if sug:
        lines.append(f"\n**Suggestions:** {len(sug)} actionable")
        for s in sug:
            lines.append(f"  \u2022 {s.get('title', '')}")

    return "\n".join(lines)
