"""Per-BID call summary prompt configuration (opt-in; default preserves legacy behavior)."""

from __future__ import annotations

from typing import Any, Dict, Optional, Tuple

SUMMARY_MODES = frozenset({"default", "discovery_recap", "custom"})
DEFAULT_OVERALL_SUMMARY_HINT = "<5-6 sentence summary of the call>"
MAX_SUMMARY_INSTRUCTIONS_LEN = 8000

DISCOVERY_RECAP_INSTRUCTIONS = """Write overall_summary in 4-6 sentences total:
1) One sentence: call purpose, overall tone, and outcome.
2) Remaining sentences: for each APPLICABLE quality parameter above, briefly state what the agent asked or did and what the customer answered (use transcript facts only — team size, CRM/tools, budget, timeline, etc. when relevant to that parameter).
Use phrasing like "Agent inquired about …; customer said …" or "not covered on this call" when the topic was not discussed.
Do not list parameter names, scores, or bullet points. Do not invent facts not supported by the transcript or parameter evaluation."""

DISCOVERY_RECAP_BASIC_INSTRUCTIONS = """Write overall_summary in 4-6 sentences total:
1) One sentence: call purpose, overall tone, and outcome.
2) Remaining sentences: key topics from the transcript (e.g. team size, CRM/tools, budget, timeline, needs) — what the agent asked and what the customer answered, or note if not discussed.
Use phrasing like "Agent inquired about …; customer said …". Use transcript facts only. No bullet lists."""


def normalize_summary_mode(mode: Optional[str]) -> str:
    value = (mode or "default").strip().lower()
    return value if value in SUMMARY_MODES else "default"


def resolve_summary_prompt_parts(
    pipeline_config: Optional[Dict[str, Any]],
    *,
    has_quality_parameters: bool = True,
) -> Tuple[str, str]:
    """
    Return (optional_summary_config_block, overall_summary_json_hint).

    When mode is 'default', returns ("", DEFAULT_OVERALL_SUMMARY_HINT) so the
    analysis prompt is byte-for-byte equivalent to the legacy template.

    has_quality_parameters=False uses transcript-based discovery wording (short
    calls and fallback analysis without a parameter list).
    """
    cfg = pipeline_config or {}
    mode = normalize_summary_mode(cfg.get("summary_mode"))
    if mode == "default":
        return "", DEFAULT_OVERALL_SUMMARY_HINT

    if mode == "discovery_recap":
        instructions = (
            DISCOVERY_RECAP_INSTRUCTIONS
            if has_quality_parameters
            else DISCOVERY_RECAP_BASIC_INSTRUCTIONS
        )
        hint = (
            "<4-6 sentences per SUMMARY CONFIG: general call context plus "
            "what was asked/answered per applicable quality parameters>"
            if has_quality_parameters
            else "<4-6 sentences per SUMMARY CONFIG: general context plus key ask/answer topics from the transcript>"
        )
    else:
        custom = (cfg.get("summary_instructions") or "").strip()
        if not custom:
            return "", DEFAULT_OVERALL_SUMMARY_HINT
        instructions = custom[:MAX_SUMMARY_INSTRUCTIONS_LEN]
        hint = "<follow SUMMARY CONFIG above for overall_summary>"

    block = (
        "SUMMARY CONFIG (overall_summary field only — scoring and other JSON fields unchanged):\n"
        f"{instructions}"
    )
    return block, hint


def load_summary_pipeline_config(db_handler: Any, bid: str) -> Optional[Dict[str, Any]]:
    try:
        db_handler.ensure_business_pipeline_config_table()
        return db_handler.get_pipeline_config(bid)
    except Exception:
        return None
