# Copyright (c) 2025 Patrick Motsch
# All rights reserved.
"""
Teamsbot Feature - Configuration utilities.
Loads and manages bot configuration from FeatureInstance.config.
"""

import logging
from typing import Optional, Dict, Any

from .datamodelTeamsbot import TeamsbotConfig

logger = logging.getLogger(__name__)


def loadConfigFromInstance(instanceId: str) -> TeamsbotConfig:
    """
    Load TeamsbotConfig from a FeatureInstance's config JSONB field.
    Falls back to default config if not found or invalid.
    """
    try:
        from modules.interfaces.interfaceDbApp import getRootInterface
        from modules.interfaces.interfaceFeatures import getFeatureInterface

        rootInterface = getRootInterface()
        featureInterface = getFeatureInterface(rootInterface.db)
        instance = featureInterface.getFeatureInstance(instanceId)

        if not instance:
            logger.warning(f"FeatureInstance '{instanceId}' not found, using default config")
            return TeamsbotConfig()

        configDict = instance.get("config") if isinstance(instance, dict) else getattr(instance, "config", None)

        if configDict and isinstance(configDict, dict):
            # Extract teamsbot-specific config if nested
            teamsbotConfig = configDict.get("teamsbot", configDict)
            return TeamsbotConfig(**teamsbotConfig)

    except Exception as e:
        logger.error(f"Error loading teamsbot config for instance '{instanceId}': {e}")

    return TeamsbotConfig()


def saveConfigToInstance(instanceId: str, config: TeamsbotConfig) -> bool:
    """Save TeamsbotConfig to FeatureInstance.config JSONB field."""
    try:
        from modules.interfaces.interfaceDbApp import getRootInterface
        from modules.interfaces.interfaceFeatures import getFeatureInterface

        rootInterface = getRootInterface()
        featureInterface = getFeatureInterface(rootInterface.db)

        featureInterface.updateFeatureInstanceConfig(instanceId, config.model_dump())
        logger.info(f"Teamsbot config saved for instance '{instanceId}'")
        return True

    except Exception as e:
        logger.error(f"Error saving teamsbot config for instance '{instanceId}': {e}")
        return False
