"""Prompt templates for summarization — builds LangChain prompts from domain config."""

from __future__ import annotations

from typing import Optional

from langchain_core.messages import SystemMessage
from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate

from res_sum.schemas import DomainConfig


# ---------------------------------------------------------------------------
# Default fallback prompt (when no domain CoT is available)
# ---------------------------------------------------------------------------

DEFAULT_SYSTEM_PROMPT = """You are an expert research analyst. Provide a clear, comprehensive summary of the following scientific text. Focus on:
1. The research question or hypothesis
2. Key methods used
3. Main findings and their significance
4. Limitations and future directions

Be precise and include specific details (statistics, measurements) when available."""


def build_summarization_prompt(
    user_prompt: Optional[str] = None,
    domain_config: Optional[DomainConfig] = None,
    use_cot: bool = True,
) -> ChatPromptTemplate:
    """Build a ChatPromptTemplate for summarization.

    Priority:
    1. If user_prompt is provided, use it as the system message.
    2. If use_cot and domain_config has a CoT prompt, use that.
    3. Fall back to DEFAULT_SYSTEM_PROMPT.

    Args:
        user_prompt: Custom user-provided prompt (overrides everything).
        domain_config: Domain config with optional CoT template.
        use_cot: Whether to use Chain-of-Thought prompting.

    Returns:
        A ChatPromptTemplate with system + human message slots.
    """
    if user_prompt:
        system_content = user_prompt
    elif use_cot and domain_config and domain_config.cot_prompt:
        system_content = domain_config.cot_prompt
    else:
        system_content = DEFAULT_SYSTEM_PROMPT

    return ChatPromptTemplate.from_messages([
        SystemMessage(content=system_content),
        HumanMessagePromptTemplate.from_template("{text}"),
    ])
