"""
Shared serialization helpers for question/log persistence.

These helpers intentionally mirror save-prompt semantics:
- SQL: ``dict`` / ``list`` -> JSON string, scalar -> ``str``.
- API fields: ``list`` -> JSON string, scalar -> ``str``.
"""
from __future__ import annotations

import json
from typing import Any, Optional


def sql_to_db_value(sql: Any, *, none_default: Optional[str] = None) -> Optional[str]:
    """
    Convert SQL payload to DB text value.

    Args:
        sql: SQL payload (str/list/dict/other).
        none_default: value used when ``sql`` is ``None``.
    """
    if sql is None:
        return none_default
    if isinstance(sql, (dict, list)):
        return json.dumps(sql)
    return str(sql)


def api_field_to_db_value(val: Any, *, none_default: Optional[str] = None) -> Optional[str]:
    """
    Convert API payload field (endpoint/params/validator) to DB text value.
    """
    if val is None:
        return none_default
    if isinstance(val, list):
        return json.dumps(val)
    return str(val)
