"""OpenAI classifier: is this inbound email a real interested / positive sales reply?"""

from __future__ import annotations

import json
import logging
import re
from functools import lru_cache
from typing import Any

from app.config import settings

logger = logging.getLogger("inbound_ai")

_SYSTEM = """You classify inbound email for a B2B sales CRM.

Decide if the sender is a real human prospect showing interest in buying, booking a call,
requesting pricing/demo, or otherwise positively engaging with a sales conversation.

Return ONLY compact JSON:
{"label":"positive"|"negative"|"neutral","reason":"short phrase","confidence":0.0-1.0}

Rules:
- positive: genuine interest, ask for pricing/demo/call, want to proceed, warm reply to outreach
- negative: not interested, unsubscribe, spam, cold outreach TO us, newsletters, LinkedIn digests,
  GitHub/Dependabot, product updates, receipts, automated system mail
- neutral: unclear, FYI only, out-of-office, or not a sales opportunity
- Prefer negative/neutral when unsure. Never mark mass marketing as positive.
"""

_AUTOMATED_FROM_RE = re.compile(
    r"(noreply|no-reply|donotreply|do-not-reply|mailer-daemon|notifications?|"
    r"updates?|news(letter)?|digest|marketing|bounce|support@|"
    r"linkedin\.com|github\.com|google\.com|facebookmail|twitter\.com)",
    re.I,
)


@lru_cache(maxsize=4)
def _build_client(api_key: str, timeout: float):
    from openai import OpenAI

    return OpenAI(api_key=api_key, timeout=timeout, max_retries=1)


def ai_classify_enabled() -> bool:
    return bool(settings.inbound_mail_ai_enabled and settings.openai_api_key)


def looks_automated_sender(from_email: str, from_name: str = "") -> bool:
    blob = f"{from_email or ''} {from_name or ''}"
    return bool(_AUTOMATED_FROM_RE.search(blob))


def classify_interest_with_openai(
    *,
    subject: str,
    body: str,
    from_email: str = "",
    from_name: str = "",
) -> dict[str, Any]:
    """Return label positive|negative|neutral plus reason/confidence.

    On missing key / API failure → neutral (do not auto-create lead).
    """
    if looks_automated_sender(from_email, from_name):
        return {
            "label": "negative",
            "reason": "automated-sender",
            "confidence": 0.95,
            "source": "heuristic",
        }

    if not ai_classify_enabled():
        return {
            "label": "neutral",
            "reason": "ai-disabled",
            "confidence": 0.0,
            "source": "none",
        }

    subject = (subject or "")[:500]
    body = (body or "")[:3500]
    user = (
        f"From: {from_name or ''} <{from_email or ''}>\n"
        f"Subject: {subject}\n\n"
        f"Body:\n{body}"
    )

    try:
        client = _build_client(settings.openai_api_key, settings.openai_timeout_seconds)
        resp = client.chat.completions.create(
            model=settings.openai_model or "gpt-4o-mini",
            temperature=0,
            response_format={"type": "json_object"},
            messages=[
                {"role": "system", "content": _SYSTEM},
                {"role": "user", "content": user},
            ],
        )
        raw = (resp.choices[0].message.content or "").strip()
        data = json.loads(raw) if raw else {}
    except Exception as exc:  # noqa: BLE001
        logger.warning("OpenAI inbound classify failed: %s", exc)
        return {
            "label": "neutral",
            "reason": f"ai-error:{type(exc).__name__}",
            "confidence": 0.0,
            "source": "error",
        }

    label = str(data.get("label") or "neutral").strip().lower()
    if label not in {"positive", "negative", "neutral"}:
        label = "neutral"
    try:
        confidence = float(data.get("confidence") or 0)
    except (TypeError, ValueError):
        confidence = 0.0
    confidence = max(0.0, min(1.0, confidence))
    reason = str(data.get("reason") or label)[:200]
    return {
        "label": label,
        "reason": reason,
        "confidence": confidence,
        "source": "openai",
    }
