"""Message Refiner — polishes draft messages for natural human tone.

After the initial LLM generation, this separate pass takes the draft
and refines it to sound like a real person wrote it (not AI).
The Refiner preserves the original intent, personalization, and
voice match while making the prose more natural and crisp.

From the original AI in Charge `improve_message()` (message.py lines 237-281).
"""

from __future__ import annotations

import logging
from typing import Any

from .length_fixer import shorten_to_limit
from .llm import LLMClient
from .prompt_loader import get_prompt_temperature, has_prompt, render_prompt

logger = logging.getLogger(__name__)

IMPROVE_SYSTEM = """You are the Message Refiner for an AI LinkedIn SDR.
Your sole job is to take the draft outreach message and polish it so it reads like a crisp, natural human text.

Rules:
- PRESERVE the original intent, personalization details, and CTA
- PRESERVE the sender's voice — tone, formality, vocabulary
- REMOVE any AI-sounding phrases ("I noticed", "I came across", "I'd love to")
- REMOVE any salesy language ("leverage", "synergy", "exciting opportunity")
- Make sentences punchier and more natural
- Keep the same character limit as the original
- Output ONLY the refined message text. No explanation, no quotes, no formatting."""

IMPROVE_PROMPT = """Polish this {message_type} message to sound more natural and human.

## DRAFT MESSAGE
{draft}

## SENDER'S VOICE
Tone: {voice_tone}
Sentence style: {voice_sentence}
No-go words: {voice_nogo}

## CONSTRAINTS
- MAXIMUM {max_chars} characters (hard limit)
- MUST sound like the sender wrote it naturally
- MUST preserve the prospect-specific details and CTA
- Remove any AI-tells or salesy phrases
- Keep it crisp and genuine

## OUTPUT
Write ONLY the refined message text. Nothing else."""


async def improve_message(
    draft: str,
    voice_signature: dict[str, Any],
    message_type: str = "invitation",
    max_chars: int = 200,
) -> str:
    """Polish a draft message to sound more natural and human.

    This is the "Improve" stage in the Generate → Improve → Validate → Fix pipeline.

    Args:
        draft: The raw generated message to improve.
        voice_signature: User's voice analysis (tone, vocabulary, patterns).
        message_type: Type of message: "invitation", "followup", or "comment".
        max_chars: Character limit for the message.

    Returns:
        Improved message string. Returns original draft if improvement fails.
    """
    if not draft or not draft.strip():
        return draft

    # Route through backend if in backend mode and no local LLM key
    from ..config import has_local_llm_key, is_backend_mode
    if is_backend_mode() and not has_local_llm_key():
        from ..linkedin import get_linkedin_client
        client = get_linkedin_client()
        try:
            return await client.improve_message(
                draft=draft,
                voice=voice_signature,
                message_type=message_type,
                max_chars=max_chars,
            )
        except Exception as e:
            logger.warning(f"Backend improve_message failed, returning draft: {e}")
            return draft
        finally:
            await client.close()

    tpl_vars = {
        "message_type": message_type,
        "draft": draft,
        "voice_tone": voice_signature.get("tone", "Professional, direct"),
        "voice_sentence": voice_signature.get("sentence_length", "Medium"),
        "voice_nogo": voice_signature.get("no_go", "Generic sales phrases"),
        "max_chars": str(max_chars),
    }

    # v63 path: use JSON prompt template
    if has_prompt("message_improve"):
        logger.debug("Using v63 message_improve prompt")
        prompt = render_prompt("message_improve", tpl_vars)
        temperature = get_prompt_temperature("message_improve")
    else:
        logger.debug("Using legacy message_improve prompt")
        prompt = IMPROVE_PROMPT.format(**tpl_vars)
        temperature = 0.7

    try:
        client = LLMClient()
        improved = await client.generate(
            prompt, system=IMPROVE_SYSTEM, temperature=temperature,
        )

        # Clean up
        improved = improved.strip().strip('"').strip("'").strip()

        # Sanity checks — if the LLM returned garbage, keep the original
        if not improved or len(improved) < 10:
            logger.warning("Improve stage returned empty/short result, keeping draft")
            return draft

        # Enforce char limit (LLM-based shortening with retry)
        improved = await shorten_to_limit(improved, max_chars)

        return improved

    except Exception as e:
        logger.warning(f"Message improve failed, returning draft: {e}")
        return draft
