"""Shared Mcube phone validation helpers (Classic + 2.0)."""

from __future__ import annotations

import re
from typing import Any, Dict, Optional

VALID_PHONE_SQL_PATTERN = r"^[+]?[0-9]{6,}$"


def valid_phone_sql(expr: str) -> str:
    """SQL expression: return trimmed phone only when 6+ digits, else NULL."""
    trimmed = f"TRIM(CAST({expr} AS CHAR))"
    return (
        f"CASE WHEN {expr} IS NOT NULL AND {trimmed} REGEXP '{VALID_PHONE_SQL_PATTERN}' "
        f"THEN {trimmed} ELSE NULL END"
    )


def phone_digits(value: Any) -> str:
    return "".join(ch for ch in str(value or "") if ch.isdigit())


def is_plausible_phone(value: Any) -> bool:
    return len(phone_digits(value)) >= 6


def is_numeric_agent_token(value: Any) -> bool:
    """True when value looks like a Mcube eid/extension, not a display name."""
    text = str(value or "").strip()
    return bool(text) and text.isdigit() and len(text) <= 6


def sanitize_agent_callinfo(agent_name: Any, agent_callinfo: Any) -> str:
    """Drop bare numeric agent ids from agent_callinfo when no agent name is present."""
    name = str(agent_name or "").strip()
    line = str(agent_callinfo or "").strip()
    if name:
        return line
    if is_numeric_agent_token(line):
        return ""
    return line


def phone_from_callid(callid: Any) -> str:
    digits = phone_digits(callid)
    if len(digits) < 10:
        return ""
    return digits[:10]


def is_likely_trunk_did(value: Any) -> bool:
    """True for toll-free / virtual numbers that must not be used as lead phones."""
    digits = phone_digits(value)
    if len(digits) < 10:
        return False
    if digits.startswith("080"):
        return True
    if digits.startswith("1800"):
        return True
    return False


def pick_mcube_customer_phone(row: Dict[str, Any]) -> str:
    """
    Resolve customer phone from a Mcube source/raw row.

    Mcube Classic inbound: callfrom is usually the customer.
    Mcube 2.0 inbound: callfrom is often an agent extension (e.g. 421) and callto
    holds the customer number.

    clicktocalldid is a virtual DID / click-to-call bridge number. It must not be
    used as the customer phone or unrelated outbound calls collapse under one lead.
    """
    explicit = str(row.get("customer_callinfo") or row.get("customer_phone") or "").strip()
    if is_plausible_phone(explicit) and not is_likely_trunk_did(explicit):
        return explicit

    direction = str(row.get("direction") or "inbound").strip().lower()
    callto = str(row.get("callto") or "").strip()
    callfrom = str(row.get("callfrom") or "").strip()
    callid_phone = phone_from_callid(row.get("callid"))

    resolved = ""
    if direction == "outbound":
        if is_plausible_phone(callto):
            resolved = callto
        elif len(phone_digits(callfrom)) >= 10:
            resolved = callfrom
    else:
        if is_plausible_phone(callfrom) and not is_numeric_agent_token(callfrom):
            resolved = callfrom
        elif is_plausible_phone(callto) and not is_likely_trunk_did(callto):
            resolved = callto
        elif is_plausible_phone(callfrom):
            resolved = callfrom
        elif is_plausible_phone(callto):
            resolved = callto

    if not resolved:
        for value in (callto, callfrom):
            if value and is_plausible_phone(value) and not is_likely_trunk_did(value):
                resolved = value
                break

    if callid_phone and is_plausible_phone(callid_phone) and not is_likely_trunk_did(callid_phone):
        if not resolved or is_likely_trunk_did(resolved):
            return callid_phone

    if resolved and is_likely_trunk_did(resolved):
        return callid_phone if is_plausible_phone(callid_phone) else ""

    return resolved


def resolve_customer_phone(
    row: Dict[str, Any],
    *,
    default: str = "",
) -> str:
    """Best-effort customer phone for display/backfill."""
    for key in ("lead_phone",):
        value = str(row.get(key) or "").strip()
        if is_plausible_phone(value):
            return value

    resolved = pick_mcube_customer_phone(row)
    if is_plausible_phone(resolved):
        return resolved

    for key in ("customer_callinfo", "customer_phone", "lead_phone"):
        value = str(row.get(key) or "").strip()
        if value:
            return value
    return default
