from __future__ import annotations

from sqlalchemy import func, select
from sqlalchemy.orm import Session

from app.models.whatsapp import WhatsAppContact

UNKNOWN_CONTACT_NAMES = {"", "sconosciuto", "unknown"}


def normalize_contact_phone(value: str | None) -> str | None:
    if not value:
        return None
    trimmed = value.strip()
    if not trimmed:
        return None
    has_plus = trimmed.startswith("+")
    digits = "".join(character for character in trimmed if character.isdigit())
    if len(digits) < 6:
        return None
    return f"+{digits}" if has_plus else digits


def normalize_contact_name(value: str | None) -> str | None:
    if not value:
        return None
    cleaned = " ".join(value.strip().split())
    if cleaned.casefold() in UNKNOWN_CONTACT_NAMES:
        return None
    return cleaned


def remember_whatsapp_contact(*, phone: str | None, display_name: str | None, db: Session) -> WhatsAppContact | None:
    normalized_phone = normalize_contact_phone(phone)
    if normalized_phone is None:
        return None

    contact = db.scalar(select(WhatsAppContact).where(WhatsAppContact.contact_phone == normalized_phone))
    normalized_name = normalize_contact_name(display_name)
    if contact is None:
        contact = WhatsAppContact(
            contact_phone=normalized_phone,
            display_name=normalized_name or normalized_phone,
        )
        db.add(contact)
        db.flush()
        return contact

    if normalized_name:
        contact.display_name = normalized_name
    contact.last_seen_at = func.now()
    db.flush()
    return contact


def get_known_whatsapp_contact_name(phone: str | None, db: Session) -> str | None:
    normalized_phone = normalize_contact_phone(phone)
    if normalized_phone is None:
        return None
    contact = db.scalar(select(WhatsAppContact).where(WhatsAppContact.contact_phone == normalized_phone))
    if contact is None:
        return None
    return normalize_contact_name(contact.display_name)
