"""Deterministic PCA metric answers from panel_data — exact DB-backed numbers before LLM."""

import re
from typing import Any, Dict, Optional, Tuple


def _normalize(text: str) -> str:
    return re.sub(r"\s+", " ", str(text or "").lower()).strip()


def _period_stats(panel_data: Dict[str, Any], period_key: str) -> Dict[str, Any]:
    periods = panel_data.get("periods") or {}
    bundle = periods.get(period_key) or {}
    stats = bundle.get("stats") or {}
    if stats:
        return stats
    focus = panel_data.get("question_focus") or {}
    if focus.get("label") == period_key or (
        period_key == "today" and focus.get("label") in ("today",)
    ):
        return focus.get("stats") or {}
    return {}


def _pick_period(message: str) -> str:
    text = _normalize(message)
    if re.search(r"\btoday\b", text):
        return "today"
    if re.search(r"\byesterday\b", text):
        return "yesterday"
    if re.search(r"\bthis week\b|\blast 7 days\b|\bpast week\b", text):
        return "last_7_days"
    if re.search(r"\bthis month\b|\bcurrent month\b", text):
        return "this_month"
    if re.search(r"\ball[- ]time\b|\btotal\b|\boverall\b|\blifetime\b", text):
        return "all_time"
    return "all_time"


def _period_label(panel_data: Dict[str, Any], period_key: str) -> str:
    ref = panel_data.get("reference") or {}
    today = ref.get("today_ist") or "today"
    labels = {
        "today": f"today ({today}, IST)",
        "yesterday": "yesterday",
        "last_7_days": "the last 7 days",
        "this_month": "this month",
        "all_time": "all time",
    }
    filters = panel_data.get("filters") or {}
    if period_key == "all_time" and (filters.get("date_from") or filters.get("date_to")):
        return "the selected dashboard date range"
    return labels.get(period_key, period_key)


def _top_agent_by_calls(panel_data: Dict[str, Any], period_key: str) -> Optional[Dict[str, Any]]:
    periods = panel_data.get("periods") or {}
    bundle = periods.get(period_key) or {}
    agents = bundle.get("agent_call_counts") or panel_data.get("agent_call_counts") or []
    if bundle.get("top_agent_by_call_volume"):
        return bundle["top_agent_by_call_volume"]
    return agents[0] if agents else None


def _top_agent_by_quality(panel_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    top = panel_data.get("top_agent_by_quality_score")
    if top:
        return top
    board = panel_data.get("agent_quality_leaderboard") or []
    return board[0] if board else None


def compute_panel_answer(
    message: str, panel_data: Optional[Dict[str, Any]]
) -> Tuple[Optional[str], Dict[str, Any], float]:
    """
    Return (direct_answer, computed_facts, confidence).
    direct_answer is set for high-confidence metric questions answered from DB panel_data.
    """
    facts: Dict[str, Any] = {}
    if not panel_data or not str(message or "").strip():
        return None, facts, 0.0

    text = _normalize(message)
    period_key = _pick_period(message)
    stats = _period_stats(panel_data, period_key)
    if not stats and period_key != "all_time":
        stats = _period_stats(panel_data, "all_time")
        period_key = "all_time"
    if not stats:
        stats = (panel_data.get("dashboard_stats") or {})
    if not stats:
        return None, facts, 0.0

    period_name = _period_label(panel_data, period_key)
    ref = panel_data.get("reference") or {}
    facts = {
        "period": period_key,
        "period_label": period_name,
        "timezone": ref.get("timezone") or "Asia/Kolkata",
        "today_ist": ref.get("today_ist"),
        "stats": stats,
    }

    # --- Total calls ---
    if re.search(
        r"(how many|total|number of|count of).*(call|calls)|"
        r"(call|calls).*(how many|total|count|number)",
        text,
    ):
        if re.search(r"\banswered\b", text) and not re.search(r"\bmissed\b|\bnot answered\b", text):
            val = int(stats.get("answered_total") or 0)
            facts["metric"] = "answered_calls"
            facts["value"] = val
            return (
                f"For {period_name}, this business has **{val}** answered call{'s' if val != 1 else ''}.",
                facts,
                0.95,
            )
        if re.search(r"\bmissed\b|\bnot answered\b|\bno answer\b", text):
            missed = int(stats.get("inbound_not_answered") or 0) + int(
                stats.get("outbound_not_answered") or 0
            )
            facts["metric"] = "missed_calls"
            facts["value"] = missed
            return (
                f"For {period_name}, this business has **{missed}** missed / not-answered call{'s' if missed != 1 else ''}.",
                facts,
                0.92,
            )
        if re.search(r"\binbound\b", text):
            val = int(stats.get("inbound_total") or 0)
            facts["metric"] = "inbound_calls"
            facts["value"] = val
            return (
                f"For {period_name}, this business has **{val}** inbound call{'s' if val != 1 else ''}.",
                facts,
                0.93,
            )
        if re.search(r"\boutbound\b", text):
            val = int(stats.get("outbound_total") or 0)
            facts["metric"] = "outbound_calls"
            facts["value"] = val
            return (
                f"For {period_name}, this business has **{val}** outbound call{'s' if val != 1 else ''}.",
                facts,
                0.93,
            )
        val = int(stats.get("total_calls") or 0)
        facts["metric"] = "total_calls"
        facts["value"] = val
        return (
            f"For {period_name}, this business has **{val}** total call{'s' if val != 1 else ''}.",
            facts,
            0.95,
        )

    # --- Top agent by call volume ---
    if re.search(
        r"(which|who).*(agent|agents).*(most|max|highest|top|maximum).*(call|calls)|"
        r"(most|max|highest|top).*(call|calls).*(agent|agents)|"
        r"agent.*(most|max|highest).*(call|calls)",
        text,
    ):
        top = _top_agent_by_calls(panel_data, period_key)
        if not top:
            return (
                f"I don't have agent call-count data for {period_name} in the current filters.",
                facts,
                0.85,
            )
        name = top.get("agent_name") or "Unknown"
        count = int(top.get("total_calls") or 0)
        facts["metric"] = "top_agent_by_calls"
        facts["agent_name"] = name
        facts["value"] = count
        return (
            f"For {period_name}, **{name}** has the highest call volume with **{count}** call{'s' if count != 1 else ''}.",
            facts,
            0.94,
        )

    # --- Best agent by quality ---
    if re.search(
        r"(best|top|highest).*(agent|agents).*(quality|score|perform)|"
        r"(quality|score).*(leader|leaderboard|ranking|best)|"
        r"agent.*(leaderboard|ranking|best perform)",
        text,
    ):
        top = _top_agent_by_quality(panel_data)
        if not top:
            return (
                "I don't have agent quality leaderboard data for the current filters yet.",
                facts,
                0.85,
            )
        name = top.get("agent_name") or "Unknown"
        score = top.get("performance_score", top.get("avg_score"))
        calls = int(top.get("total_calls") or 0)
        facts["metric"] = "top_agent_by_quality"
        facts["agent_name"] = name
        facts["performance_score"] = score
        return (
            f"**{name}** leads the agent leaderboard with a performance score of **{score}** "
            f"across **{calls}** analyzed call{'s' if calls != 1 else ''}.",
            facts,
            0.92,
        )

    # --- Average quality score ---
    if re.search(r"(average|avg|mean).*(quality|score)|quality score", text):
        score = stats.get("avg_quality_score")
        if score is None:
            return (
                f"Average quality score is not available for {period_name} in the current data.",
                facts,
                0.8,
            )
        facts["metric"] = "avg_quality_score"
        facts["value"] = score
        return (
            f"For {period_name}, the average quality score is **{score}**.",
            facts,
            0.93,
        )

    # --- Latest call ---
    if re.search(r"(latest|last|most recent).*(call|calls)", text):
        latest = panel_data.get("latest_call") or {}
        if not latest:
            calls = panel_data.get("recent_calls") or []
            latest = calls[0] if calls else {}
        if not latest:
            return (
                f"No recent calls found for {period_name}.",
                facts,
                0.88,
            )
        callid = latest.get("callid") or "—"
        agent = latest.get("agentname") or latest.get("agent_callinfo") or "Unknown"
        when = latest.get("call_starttime") or ""
        facts["metric"] = "latest_call"
        facts["call_id"] = callid
        return (
            f"The latest call is **{callid}** by **{agent}**"
            + (f" at {when}." if when else "."),
            facts,
            0.9,
        )

    return None, facts, 0.0
