import json
from .cache import get_redis
from .database import get_pool, get_system_pool, _has_split_databases
import aiomysql

WIKI_CONFIG_PREFIX = "bff:wiki_feedback:"

DEFAULT_MIN_CONTENT_LENGTH = 10
DEFAULT_MAX_CONTENT_LENGTH = 100000
DEFAULT_TITLE_FORMAT = "知识反哺-{date}"
DEFAULT_DIRECTORY_ID = None


async def get_wiki_feedback_config() -> dict:
    r = await get_redis()
    cached = await r.get(f"{WIKI_CONFIG_PREFIX}config")
    if cached:
        return json.loads(cached)

    pool = await get_system_pool() if _has_split_databases() else await get_pool()
    config = {}
    async with pool.acquire() as conn:
        async with conn.cursor(aiomysql.DictCursor) as cur:
            await cur.execute(
                "SELECT config_key, config_value FROM system_configs WHERE category = 'wiki_feedback'"
            )
            rows = await cur.fetchall()

    for row in rows:
        key = row["config_key"].replace("wiki_feedback.", "")
        val = row["config_value"]
        if key in ("min_content_length", "max_content_length", "default_directory_id"):
            config[key] = int(val)
        else:
            config[key] = val

    result = {
        "min_content_length": config.get("min_content_length", DEFAULT_MIN_CONTENT_LENGTH),
        "max_content_length": config.get("max_content_length", DEFAULT_MAX_CONTENT_LENGTH),
        "title_format": config.get("title_format", DEFAULT_TITLE_FORMAT),
        "default_directory_id": config.get("default_directory_id", DEFAULT_DIRECTORY_ID),
    }

    try:
        await r.setex(f"{WIKI_CONFIG_PREFIX}config", 300, json.dumps(result))
    except Exception:
        pass

    return result
