"""Persist WhatsApp integration settings on the AppSetting singleton meta_data."""
from __future__ import annotations

import json
from typing import Any, Dict, Optional

from sqlalchemy.orm import Session

from app.models.app_setting import AppSetting

WHATSAPP_META_KEY = "whatsapp_integration"

DEFAULTS: Dict[str, str] = {
    "whatsapp_enabled": "false",
    "whatsapp_api_provider": "whatsapp_business",
    "whatsapp_business_token": "",
    "whatsapp_business_phone_id": "",
    "twilio_account_sid": "",
    "twilio_auth_token": "",
    "twilio_whatsapp_number": "",
}


def _load_meta(db: Session) -> Dict[str, Any]:
    inst = AppSetting.get_instance(db)
    try:
        return json.loads(inst.meta_data) if inst.meta_data else {}
    except json.JSONDecodeError:
        return {}


def get_whatsapp_settings(db: Session) -> Dict[str, str]:
    meta = _load_meta(db)
    stored = meta.get(WHATSAPP_META_KEY) or {}
    out = dict(DEFAULTS)
    if isinstance(stored, dict):
        for k in out:
            if k in stored and stored[k] is not None:
                out[k] = str(stored[k])
    return out


def save_whatsapp_settings(db: Session, updates: Dict[str, Any]) -> Dict[str, str]:
    inst = AppSetting.get_instance(db)
    meta = _load_meta(db)
    current = meta.get(WHATSAPP_META_KEY) or {}
    if not isinstance(current, dict):
        current = {}
    for key in DEFAULTS:
        if key in updates and updates[key] is not None:
            current[key] = str(updates[key])
    meta[WHATSAPP_META_KEY] = current
    inst.meta_data = json.dumps(meta)
    db.commit()
    return get_whatsapp_settings(db)


def mask_secret(value: Optional[str], show: int = 4) -> str:
    if not value:
        return ""
    v = str(value)
    if len(v) <= show:
        return "*" * len(v)
    return "*" * (len(v) - show) + v[-show:]
