# Copyright (c) 2025 Patrick Motsch
# All rights reserved.
"""
AIChat Feature Container - Main Module.
Handles feature initialization and RBAC catalog registration.

AIChat is the dynamic chat workflow feature that handles:
- AI-powered document processing
- Dynamic workflow execution
- Automation definitions
"""

import logging
from typing import Dict, List, Any

logger = logging.getLogger(__name__)

# Feature metadata
FEATURE_CODE = "chatworkflow"
FEATURE_LABEL = {"en": "Chat Workflow", "de": "Chat-Workflow", "fr": "Workflow de Chat"}
FEATURE_ICON = "mdi-message-cog"

# UI Objects for RBAC catalog
UI_OBJECTS = [
    {
        "objectKey": "ui.feature.aichat.workflows",
        "label": {"en": "Workflows", "de": "Workflows", "fr": "Workflows"},
        "meta": {"area": "workflows"}
    },
    {
        "objectKey": "ui.feature.aichat.automations",
        "label": {"en": "Automations", "de": "Automatisierungen", "fr": "Automatisations"},
        "meta": {"area": "automations"}
    },
    {
        "objectKey": "ui.feature.aichat.logs",
        "label": {"en": "Logs", "de": "Logs", "fr": "Journaux"},
        "meta": {"area": "logs"}
    },
]

# Resource Objects for RBAC catalog
RESOURCE_OBJECTS = [
    {
        "objectKey": "resource.feature.aichat.workflow.start",
        "label": {"en": "Start Workflow", "de": "Workflow starten", "fr": "Démarrer workflow"},
        "meta": {"endpoint": "/api/chat/playground/start", "method": "POST"}
    },
    {
        "objectKey": "resource.feature.aichat.workflow.stop",
        "label": {"en": "Stop Workflow", "de": "Workflow stoppen", "fr": "Arrêter workflow"},
        "meta": {"endpoint": "/api/chat/playground/stop/{workflowId}", "method": "POST"}
    },
    {
        "objectKey": "resource.feature.aichat.workflow.delete",
        "label": {"en": "Delete Workflow", "de": "Workflow löschen", "fr": "Supprimer workflow"},
        "meta": {"endpoint": "/api/chat/playground/workflow/{workflowId}", "method": "DELETE"}
    },
]

# Template roles for this feature
TEMPLATE_ROLES = [
    {
        "roleLabel": "workflow-admin",
        "description": {
            "en": "Workflow Administrator - Full access to workflow configuration and execution",
            "de": "Workflow-Administrator - Vollzugriff auf Workflow-Konfiguration und Ausführung",
            "fr": "Administrateur workflow - Accès complet à la configuration et exécution"
        }
    },
    {
        "roleLabel": "workflow-editor",
        "description": {
            "en": "Workflow Editor - Create and modify workflows",
            "de": "Workflow-Editor - Workflows erstellen und bearbeiten",
            "fr": "Éditeur workflow - Créer et modifier les workflows"
        }
    },
    {
        "roleLabel": "workflow-viewer",
        "description": {
            "en": "Workflow Viewer - View workflows and execution results",
            "de": "Workflow-Betrachter - Workflows und Ausführungsergebnisse einsehen",
            "fr": "Visualiseur workflow - Consulter les workflows et résultats"
        }
    },
]


def getFeatureDefinition() -> Dict[str, Any]:
    """Return the feature definition for registration."""
    return {
        "code": FEATURE_CODE,
        "label": FEATURE_LABEL,
        "icon": FEATURE_ICON
    }


def getUiObjects() -> List[Dict[str, Any]]:
    """Return UI objects for RBAC catalog registration."""
    return UI_OBJECTS


def getResourceObjects() -> List[Dict[str, Any]]:
    """Return resource objects for RBAC catalog registration."""
    return RESOURCE_OBJECTS


def getTemplateRoles() -> List[Dict[str, Any]]:
    """Return template roles for this feature."""
    return TEMPLATE_ROLES


def registerFeature(catalogService) -> bool:
    """
    Register this feature's RBAC objects in the catalog.
    
    Args:
        catalogService: The RBAC catalog service instance
        
    Returns:
        True if registration was successful
    """
    try:
        # Register UI objects
        for uiObj in UI_OBJECTS:
            catalogService.registerUiObject(
                featureCode=FEATURE_CODE,
                objectKey=uiObj["objectKey"],
                label=uiObj["label"],
                meta=uiObj.get("meta")
            )
        
        # Register Resource objects
        for resObj in RESOURCE_OBJECTS:
            catalogService.registerResourceObject(
                featureCode=FEATURE_CODE,
                objectKey=resObj["objectKey"],
                label=resObj["label"],
                meta=resObj.get("meta")
            )
        
        logger.info(f"Feature '{FEATURE_CODE}' registered {len(UI_OBJECTS)} UI objects and {len(RESOURCE_OBJECTS)} resource objects")
        return True
        
    except Exception as e:
        logger.error(f"Failed to register feature '{FEATURE_CODE}': {e}")
        return False


async def onStart(eventUser) -> None:
    """
    Called when the feature container starts.
    Initializes AI connectors for model registry.
    """
    try:
        from modules.aicore.aicoreModelRegistry import modelRegistry
        modelRegistry.ensureConnectorsRegistered()
        logger.info(f"Feature '{FEATURE_CODE}' started - AI connectors initialized")
    except Exception as e:
        logger.error(f"Feature '{FEATURE_CODE}' failed to initialize AI connectors: {e}")


async def onStop(eventUser) -> None:
    """Called when the feature container stops."""
    logger.info(f"Feature '{FEATURE_CODE}' stopped")
