"""Persistence layer for chat history and cross-session memory.

Chat history: the full conversation log — persisted in Supabase so it
survives logout/browser close, cleared only on explicit Reset.

Chat memory: short preference notes the AI discovers about a customer
(e.g. "vegetarian", "usually cooks for 5", "prefers Mikocheni delivery").
Memory survives even a chat reset — cleared only by explicit user action.
"""

import json
import logging

from accounts.supabase_client import get_client

logger = logging.getLogger(__name__)

MAX_PERSISTED_MESSAGES = 40   # keep last N messages in Supabase
MAX_MEMORY_NOTES = 20         # cap on stored memory notes


# ---------------------------------------------------------------------------
# Chat history
# ---------------------------------------------------------------------------

def load_chat_history(customer_id):
    """Returns saved chat history list from Supabase, or [] on failure."""
    try:
        resp = (
            get_client()
            .table('pickker_customer_profiles')
            .select('chat_history')
            .eq('user_id', customer_id)
            .execute()
        )
        if resp.data and resp.data[0].get('chat_history'):
            history = resp.data[0]['chat_history']
            if isinstance(history, str):
                history = json.loads(history)
            return history if isinstance(history, list) else []
    except Exception:
        logger.exception('Failed to load chat history for customer %s', customer_id)
    return []


def save_chat_history(customer_id, history):
    """Persists the chat history list to Supabase (trimmed to max)."""
    trimmed = history[-MAX_PERSISTED_MESSAGES:]
    try:
        get_client().table('pickker_customer_profiles').update(
            {'chat_history': json.dumps(trimmed)}
        ).eq('user_id', customer_id).execute()
    except Exception:
        logger.exception('Failed to save chat history for customer %s', customer_id)


def clear_chat_history(customer_id):
    """Wipes chat history from both Supabase and returns empty list."""
    try:
        get_client().table('pickker_customer_profiles').update(
            {'chat_history': json.dumps([])}
        ).eq('user_id', customer_id).execute()
    except Exception:
        logger.exception('Failed to clear chat history for customer %s', customer_id)
    return []


# ---------------------------------------------------------------------------
# Chat memory (persistent preferences)
# ---------------------------------------------------------------------------

def load_chat_memory(customer_id):
    """Returns saved memory notes list from Supabase, or [] on failure."""
    try:
        resp = (
            get_client()
            .table('pickker_customer_profiles')
            .select('chat_memory')
            .eq('user_id', customer_id)
            .execute()
        )
        if resp.data and resp.data[0].get('chat_memory'):
            memory = resp.data[0]['chat_memory']
            if isinstance(memory, str):
                memory = json.loads(memory)
            return memory if isinstance(memory, list) else []
    except Exception:
        logger.exception('Failed to load chat memory for customer %s', customer_id)
    return []


def save_chat_memory(customer_id, memory_notes):
    """Persists memory notes list to Supabase (trimmed to max)."""
    trimmed = memory_notes[-MAX_MEMORY_NOTES:]
    try:
        get_client().table('pickker_customer_profiles').update(
            {'chat_memory': json.dumps(trimmed)}
        ).eq('user_id', customer_id).execute()
    except Exception:
        logger.exception('Failed to save chat memory for customer %s', customer_id)


def clear_chat_memory(customer_id):
    """Wipes all stored memory notes."""
    try:
        get_client().table('pickker_customer_profiles').update(
            {'chat_memory': json.dumps([])}
        ).eq('user_id', customer_id).execute()
    except Exception:
        logger.exception('Failed to clear chat memory for customer %s', customer_id)
    return []
