"""
ABOS AI Worker – Email Assistant Router
==========================================
Phase 2 of the CRM upgrade program: drafts a reply, summarizes a thread, or translates text via
OpenRouter. Backend-facing only — called by Spring Boot's EmailAiController, which resolves the
tenant's stored OpenRouter key before forwarding the request here (this service never persists a
key). Read-mostly by design: every endpoint here proposes text for a human to review and send —
none of them send anything or touch Contact/Lead data, so Phase 0's resolver rules don't apply.
"""

from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException, status

from app.llm_client import call_openrouter_text
from app.schemas import (
    DraftEmailReplyRequest,
    DraftEmailReplyResponse,
    SummarizeEmailThreadRequest,
    SummarizeEmailThreadResponse,
    TranslateEmailTextRequest,
    TranslateEmailTextResponse,
)

logger = logging.getLogger(__name__)

email_ai_router = APIRouter()

_DRAFT_SYSTEM_MESSAGE = (
    "You are a professional email assistant embedded in a CRM. You draft reply bodies only — "
    "no subject line, no greeting placeholders like '[Name]' unless the sender's name is given, "
    "no markdown, no preamble like 'Here is a draft'. Respond with ONLY the reply body text."
)

_SUMMARIZE_SYSTEM_MESSAGE = (
    "You are a precise email-thread summarizer embedded in a CRM. Summarize the thread in 2-4 "
    "sentences: what it's about, what's been decided or asked, and what (if anything) is still "
    "open. Respond with ONLY the summary text — no headings, no markdown, no preamble."
)

_TRANSLATE_SYSTEM_MESSAGE = (
    "You are a precise translation assistant embedded in a CRM's email tool. Translate the given "
    "text faithfully, preserving tone and formatting (line breaks, etc). Respond with ONLY the "
    "translated text — no notes, no explanation, no original text repeated."
)


@email_ai_router.post(
    "/email/draft-reply",
    response_model=DraftEmailReplyResponse,
    status_code=status.HTTP_200_OK,
    summary="Draft a reply to an email via OpenRouter",
    tags=["Backend-Facing"],
)
async def draft_reply(request: DraftEmailReplyRequest) -> DraftEmailReplyResponse:
    user_message = (
        f"Subject: {request.subject}\n"
        f"Desired tone: {request.tone or 'professional'}\n"
        + (f"Additional instructions: {request.instructions}\n" if request.instructions else "")
        + f"\nIncoming email body:\n{request.incoming_body}\n\nWrite the reply body."
    )
    try:
        reply_body, model_used = await call_openrouter_text(
            openrouter_key=request.openrouter_key,
            system_message=_DRAFT_SYSTEM_MESSAGE,
            user_message=user_message,
            model=request.model,
        )
    except Exception as exc:
        logger.error("Draft reply generation failed: %s", exc)
        raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=f"Draft reply generation failed: {exc}") from exc

    return DraftEmailReplyResponse(reply_body=reply_body, model_used=model_used)


@email_ai_router.post(
    "/email/summarize-thread",
    response_model=SummarizeEmailThreadResponse,
    status_code=status.HTTP_200_OK,
    summary="Summarize an email thread via OpenRouter",
    tags=["Backend-Facing"],
)
async def summarize_thread(request: SummarizeEmailThreadRequest) -> SummarizeEmailThreadResponse:
    try:
        summary, model_used = await call_openrouter_text(
            openrouter_key=request.openrouter_key,
            system_message=_SUMMARIZE_SYSTEM_MESSAGE,
            user_message=f"Thread:\n{request.thread_text}",
            model=request.model,
        )
    except Exception as exc:
        logger.error("Thread summarization failed: %s", exc)
        raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=f"Thread summarization failed: {exc}") from exc

    return SummarizeEmailThreadResponse(summary=summary, model_used=model_used)


@email_ai_router.post(
    "/email/translate",
    response_model=TranslateEmailTextResponse,
    status_code=status.HTTP_200_OK,
    summary="Translate email text via OpenRouter",
    tags=["Backend-Facing"],
)
async def translate_text(request: TranslateEmailTextRequest) -> TranslateEmailTextResponse:
    try:
        translated, model_used = await call_openrouter_text(
            openrouter_key=request.openrouter_key,
            system_message=_TRANSLATE_SYSTEM_MESSAGE,
            user_message=f"Translate the following text to {request.target_language}:\n\n{request.text}",
            model=request.model,
        )
    except Exception as exc:
        logger.error("Translation failed: %s", exc)
        raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=f"Translation failed: {exc}") from exc

    return TranslateEmailTextResponse(translated_text=translated, model_used=model_used)
