"""
BizNode Daily Digest Service
==============================
Builds and sends a daily HTML email digest of all customer Telegram queries
to the owner. The email footer instructs the owner how to reply with commands
that BizNode will automatically execute via the IMAP inbox service.
"""

from __future__ import annotations

import importlib.util
import logging
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

log = logging.getLogger(__name__)

_PROJECT_ROOT = Path(__file__).resolve().parent.parent

OWNER_EMAIL = os.getenv("OWNER_EMAIL", "")


# ---------------------------------------------------------------------------
# DB loader
# ---------------------------------------------------------------------------
def _load_db():
    db_path = _PROJECT_ROOT / "memory" / "database.py"
    spec = importlib.util.spec_from_file_location("_db", str(db_path))
    mod  = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


# ---------------------------------------------------------------------------
# HTML builder
# ---------------------------------------------------------------------------

_HTML_TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<style>
  body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
          background:#f5f5f5; color:#222; margin:0; padding:0; }}
  .wrapper {{ max-width:700px; margin:0 auto; background:#fff; border-radius:8px;
              overflow:hidden; box-shadow:0 2px 8px rgba(0,0,0,.1); }}
  .header  {{ background:#1e293b; color:#fff; padding:24px 32px; }}
  .header h1 {{ margin:0; font-size:22px; }}
  .header p  {{ margin:4px 0 0; color:#94a3b8; font-size:13px; }}
  .stats   {{ display:flex; gap:0; border-bottom:1px solid #e2e8f0; }}
  .stat    {{ flex:1; padding:16px 24px; text-align:center; border-right:1px solid #e2e8f0; }}
  .stat:last-child {{ border-right:none; }}
  .stat-n  {{ font-size:28px; font-weight:700; color:#3b82f6; }}
  .stat-l  {{ font-size:12px; color:#64748b; margin-top:2px; }}
  .section {{ padding:24px 32px; }}
  .section h2 {{ font-size:14px; font-weight:600; text-transform:uppercase;
                 letter-spacing:.05em; color:#64748b; margin:0 0 16px; }}
  .qa      {{ border:1px solid #e2e8f0; border-radius:6px; margin-bottom:12px;
              overflow:hidden; }}
  .qa-meta {{ background:#f8fafc; padding:8px 14px; font-size:12px; color:#64748b;
              border-bottom:1px solid #e2e8f0; }}
  .qa-meta strong {{ color:#334155; }}
  .qa-q    {{ padding:10px 14px; font-size:14px; color:#1e293b; }}
  .qa-a    {{ padding:10px 14px; background:#f0f9ff; font-size:13px; color:#334155;
              border-top:1px solid #bae6fd; }}
  .qa-a::before {{ content:"🤖  "; }}
  .footer  {{ background:#f8fafc; border-top:2px solid #e2e8f0; padding:24px 32px; }}
  .footer h2 {{ font-size:14px; font-weight:600; color:#334155; margin:0 0 12px; }}
  .cmd     {{ background:#1e293b; color:#a5f3fc; font-family:monospace; font-size:13px;
              padding:10px 14px; border-radius:4px; margin:6px 0; }}
  .empty   {{ text-align:center; padding:48px; color:#94a3b8; font-size:15px; }}
</style>
</head>
<body>
<div class="wrapper">
  <div class="header">
    <h1>📊 BizNode Daily Digest</h1>
    <p>{date} · Automated report from your AI business agent</p>
  </div>

  <div class="stats">
    <div class="stat">
      <div class="stat-n">{total}</div>
      <div class="stat-l">Queries today</div>
    </div>
    <div class="stat">
      <div class="stat-n">{unique}</div>
      <div class="stat-l">Unique customers</div>
    </div>
    <div class="stat">
      <div class="stat-n">{blocked}</div>
      <div class="stat-l">Blocked customers</div>
    </div>
  </div>

  <div class="section">
    <h2>Customer Queries · {date}</h2>
    {qa_rows}
  </div>

  <div class="section" style="border-top:1px solid #e2e8f0;padding-top:20px">
    <h2>Telegram Group Activity</h2>
    {group_rows}
  </div>

  <div class="footer">
    <h2>📨 Reply with Instructions</h2>
    <p style="font-size:13px;color:#64748b;margin:0 0 12px">
      Reply to this email to give BizNode instructions. It checks your inbox every 15 minutes.
    </p>
    <div class="cmd">block 123456789 reason: spam</div>
    <div class="cmd">unblock 987654321</div>
    <div class="cmd">add: We now offer premium support at $299/month including...</div>
    <div class="cmd">delete: Old Pricing 2024</div>
    <p style="font-size:12px;color:#94a3b8;margin:12px 0 0">
      You can include multiple instructions in a single reply — BizNode processes all of them.
    </p>
  </div>
</div>
</body>
</html>"""

_QA_ROW = """<div class="qa">
  <div class="qa-meta">
    <strong>@{username}</strong> &nbsp;·&nbsp; ID: {telegram_id} &nbsp;·&nbsp; {time}
  </div>
  <div class="qa-q">{query}</div>
  <div class="qa-a">{response}</div>
</div>"""

_EMPTY_ROW = '<div class="empty">No customer queries today.</div>'


def build_daily_digest(date: Optional[str] = None) -> str:
    """Return a complete HTML string for today's digest email."""
    db    = _load_db()
    today = date or datetime.now(timezone.utc).strftime("%Y-%m-%d")
    logs  = db.get_query_logs(date=today, limit=500)
    stats = db.get_query_log_stats()
    blocked_count = len(db.get_blocked_customers())

    if logs:
        rows = []
        for q in logs:
            t    = (q.get("created_at") or "")[:16].replace("T", " ")
            row  = _QA_ROW.format(
                username    = q.get("username") or "unknown",
                telegram_id = q.get("telegram_id", ""),
                time        = t,
                query       = _esc(q.get("query", "")),
                response    = _esc(q.get("response", "") or "—"),
            )
            rows.append(row)
        qa_html = "\n".join(rows)
    else:
        qa_html = _EMPTY_ROW

    # Group activity section
    try:
        group_logs = [
            q for q in db.get_query_logs(date=today, limit=500)
            if q.get("source") == "telegram_group"
        ]
        group_count = len(group_logs)
        if group_count:
            top_msgs = group_logs[:5]
            top_lines = "".join(
                f'<li style="margin:4px 0;font-size:13px;color:#334155">'
                f'<strong>@{_esc(q.get("username") or "member")}</strong>: '
                f'{_esc((q.get("query") or "")[:80])}</li>'
                for q in top_msgs
            )
            group_html = (
                f'<p style="color:#334155;font-size:14px;margin:0 0 8px">'
                f'<strong>{group_count}</strong> group interactions today</p>'
                f'<ul style="padding-left:16px;margin:8px 0">{top_lines}</ul>'
            )
        else:
            group_html = '<p style="color:#94a3b8;font-size:14px">No group activity today.</p>'
    except Exception:
        group_html = '<p style="color:#94a3b8;font-size:14px">Group activity unavailable.</p>'

    return _HTML_TEMPLATE.format(
        date       = today,
        total      = stats.get("total_today", len(logs)),
        unique     = stats.get("unique_today", 0),
        blocked    = blocked_count,
        qa_rows    = qa_html,
        group_rows = group_html,
    )


def _esc(text: str) -> str:
    """Minimal HTML escaping for email content."""
    return (
        text.replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace('"', "&quot;")
    )


# ---------------------------------------------------------------------------
# Send
# ---------------------------------------------------------------------------

def send_daily_digest(date: Optional[str] = None) -> bool:
    """Build and email the daily digest to OWNER_EMAIL. Returns True on success."""
    if not OWNER_EMAIL:
        log.warning("OWNER_EMAIL not set — skipping daily digest")
        return False

    db    = _load_db()
    today = date or datetime.now(timezone.utc).strftime("%Y-%m-%d")
    stats = db.get_query_log_stats()
    total = stats.get("total_today", 0)

    html    = build_daily_digest(today)
    subject = f"BizNode Daily Digest — {today} ({total} {'query' if total == 1 else 'queries'})"

    try:
        from services.email_service import EmailService
        svc = EmailService()
        svc._email_type = "digest"
        svc.send_html_email(
            to_email = OWNER_EMAIL,
            subject  = subject,
            html_content = html,
        )
        log.info("Daily digest sent to %s (%d queries)", OWNER_EMAIL, total)
        return True
    except Exception as exc:
        log.error("Failed to send daily digest: %s", exc)
        # Log failure explicitly (send_email already logs ok/failed for successful calls)
        try:
            db.log_email_sent(
                to_addr=OWNER_EMAIL, subject=subject,
                body_preview=f"{total} queries digest",
                email_type="digest", status="failed", error_msg=str(exc),
            )
        except Exception:
            pass
        return False
