"""Shared prompt helpers for all agents."""

from __future__ import annotations

from datetime import datetime
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

from pydantic_ai import RunContext
from pydantic_ai.models.anthropic import AnthropicModelSettings

from app.agents.deps import AgentDeps

# Anthropic prompt caching: system prompt and tools are stable across requests
# (1h TTL); message history prefix is stable within a conversation (5min default).
CACHE_SETTINGS = AnthropicModelSettings(
    anthropic_cache_instructions="1h",
    anthropic_cache_tool_definitions="1h",
    anthropic_cache_messages=True,
)


def custom_prompt_suffix(ctx: RunContext[AgentDeps]) -> str:
    """Return our custom prompt suffix, or empty string."""
    suffix = ctx.deps.agent_config.custom_prompt_suffix.strip()
    if not suffix:
        return ""
    return f"Additional instructions you should follow: {suffix}"


WHATSAPP_CHANNEL_PROMPT_SUFFIX = (
    "IMPORTANT: This conversation is on WhatsApp. Follow these rules strictly:\n"
    "- Keep responses under 4096 characters\n"
    "- Do NOT use markdown formatting (no bold, italic, headers, code blocks)\n"
    "- Use plain text with line breaks for structure\n"
    "- Format options as numbered lists (1. Option A\n2. Option B)\n"
    "- Be concise and conversational\n"
    "- When presenting choices (time slots, menu items), use numbered lists"
)


def channel_prompt_suffix(ctx: RunContext[AgentDeps]) -> str:
    """Return channel-specific prompt suffix text, or empty string."""
    if ctx.deps.caller.channel == "whatsapp":
        return WHATSAPP_CHANNEL_PROMPT_SUFFIX
    return ""


def current_time_prompt(ctx: RunContext[AgentDeps]) -> str:
    """Return the current date/time in the restaurant's timezone.

    This lets the model correctly interpret relative references like
    'tomorrow', 'this weekend', or 'tonight'.
    """
    tz_name = getattr(ctx.deps, "timezone", None) or "Europe/Brussels"
    try:
        tz = ZoneInfo(tz_name)
    except (ZoneInfoNotFoundError, KeyError):
        tz_name = "Europe/Brussels"
        tz = ZoneInfo(tz_name)
    now = datetime.now(tz)
    # Use ISO date + weekday number to avoid English day/month names
    # leaking into the model's language choice.  Weekday 0=Mon..6=Sun.
    iso_date = now.strftime("%Y-%m-%d")
    time_str = now.strftime("%H:%M")
    weekday = now.weekday()  # 0=Mon
    return (
        f"[Now: {iso_date} {time_str} (weekday {weekday}, tz {tz_name}). "
        f"Resolve relative dates (today/tomorrow/weekend) from this.]"
    )
