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

import logging
from typing import Dict, List, Any

logger = logging.getLogger(__name__)

# Feature metadata
FEATURE_CODE = "chatplayground"
FEATURE_LABEL = {"en": "Chat Playground", "de": "Chat Playground", "fr": "Chat Playground"}
FEATURE_ICON = "mdi-message-text"

# UI Objects for RBAC catalog
UI_OBJECTS = [
    {
        "objectKey": "ui.feature.chatplayground.playground",
        "label": {"en": "Playground", "de": "Playground", "fr": "Playground"},
        "meta": {"area": "playground"}
    },
    {
        "objectKey": "ui.feature.chatplayground.workflows",
        "label": {"en": "Workflows", "de": "Workflows", "fr": "Workflows"},
        "meta": {"area": "workflows"}
    },
]

# Resource Objects for RBAC catalog
RESOURCE_OBJECTS = [
    {
        "objectKey": "resource.feature.chatplayground.start",
        "label": {"en": "Start Workflow", "de": "Workflow starten", "fr": "Démarrer workflow"},
        "meta": {"endpoint": "/api/chatplayground/{instanceId}/start", "method": "POST"}
    },
    {
        "objectKey": "resource.feature.chatplayground.stop",
        "label": {"en": "Stop Workflow", "de": "Workflow stoppen", "fr": "Arrêter workflow"},
        "meta": {"endpoint": "/api/chatplayground/{instanceId}/{workflowId}/stop", "method": "POST"}
    },
    {
        "objectKey": "resource.feature.chatplayground.chatData",
        "label": {"en": "Get Chat Data", "de": "Chat-Daten abrufen", "fr": "Récupérer données chat"},
        "meta": {"endpoint": "/api/chatplayground/{instanceId}/{workflowId}/chatData", "method": "GET"}
    },
]

# Template roles for this feature
# Role names MUST follow convention: {featureCode}-{roleName}
TEMPLATE_ROLES = [
    {
        "roleLabel": "chatplayground-viewer",
        "description": {
            "en": "Chat Playground Viewer - View chat playground (read-only)",
            "de": "Chat Playground Betrachter - Chat Playground ansehen (nur lesen)",
            "fr": "Visualiseur Chat Playground - Consulter le chat playground (lecture seule)"
        },
        "accessRules": [
            # UI: only playground view, NO workflows
            {"context": "UI", "item": "ui.feature.chatplayground.playground", "view": True},
            # RESOURCE: NO access (viewer cannot start/stop/access chat data)
            # DATA access (own records, read-only)
            {"context": "DATA", "item": None, "view": True, "read": "m", "create": "n", "update": "n", "delete": "n"},
        ]
    },
    {
        "roleLabel": "chatplayground-user",
        "description": {
            "en": "Chat Playground User - Use chat playground and workflows",
            "de": "Chat Playground Benutzer - Chat Playground und Workflows nutzen",
            "fr": "Utilisateur Chat Playground - Utiliser le chat playground et les workflows"
        },
        "accessRules": [
            # UI: full access to all views
            {"context": "UI", "item": "ui.feature.chatplayground.playground", "view": True},
            {"context": "UI", "item": "ui.feature.chatplayground.workflows", "view": True},
            # Resource access: can start/stop workflows and access chat data
            {"context": "RESOURCE", "item": "resource.feature.chatplayground.start", "view": True},
            {"context": "RESOURCE", "item": "resource.feature.chatplayground.stop", "view": True},
            {"context": "RESOURCE", "item": "resource.feature.chatplayground.chatData", "view": True},
            # DATA access (own records)
            {"context": "DATA", "item": None, "view": True, "read": "m", "create": "m", "update": "m", "delete": "m"},
        ]
    },
    {
        "roleLabel": "chatplayground-admin",
        "description": {
            "en": "Chat Playground Admin - Full access to chat playground",
            "de": "Chat Playground Admin - Vollzugriff auf Chat Playground",
            "fr": "Administrateur Chat Playground - Accès complet au chat playground"
        },
        "accessRules": [
            # Full UI access
            {"context": "UI", "item": None, "view": True},
            # Full resource access
            {"context": "RESOURCE", "item": None, "view": True},
            # Full DATA access
            {"context": "DATA", "item": None, "view": True, "read": "a", "create": "a", "update": "a", "delete": "a"},
        ]
    },
]


def getFeatureDefinition() -> Dict[str, Any]:
    """Return the feature definition for registration."""
    return {
        "code": FEATURE_CODE,
        "label": FEATURE_LABEL,
        "icon": FEATURE_ICON,
        "autoCreateInstance": True,  # Automatically create instance in root mandate during bootstrap
    }


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")
            )
        
        # Sync template roles to database
        _syncTemplateRolesToDb()
        
        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


def _syncTemplateRolesToDb() -> int:
    """
    Sync template roles and their AccessRules to the database.
    Creates global template roles (mandateId=None) if they don't exist.
    
    Returns:
        Number of roles created/updated
    """
    try:
        from modules.interfaces.interfaceDbApp import getRootInterface
        from modules.datamodels.datamodelRbac import Role, AccessRule, AccessRuleContext
        
        rootInterface = getRootInterface()
        
        # Get existing template roles for this feature (Pydantic models)
        existingRoles = rootInterface.getRolesByFeatureCode(FEATURE_CODE)
        # Filter to template roles (mandateId is None)
        templateRoles = [r for r in existingRoles if r.mandateId is None]
        existingRoleLabels = {r.roleLabel: str(r.id) for r in templateRoles}
        
        createdCount = 0
        for roleTemplate in TEMPLATE_ROLES:
            roleLabel = roleTemplate["roleLabel"]
            
            if roleLabel in existingRoleLabels:
                roleId = existingRoleLabels[roleLabel]
                # Ensure AccessRules exist for this role
                _ensureAccessRulesForRole(rootInterface, roleId, roleTemplate.get("accessRules", []))
            else:
                # Create new template role
                newRole = Role(
                    roleLabel=roleLabel,
                    description=roleTemplate.get("description", {}),
                    featureCode=FEATURE_CODE,
                    mandateId=None,  # Global template
                    featureInstanceId=None,
                    isSystemRole=False
                )
                createdRole = rootInterface.db.recordCreate(Role, newRole.model_dump())
                roleId = createdRole.get("id")
                
                # Create AccessRules for this role
                _ensureAccessRulesForRole(rootInterface, roleId, roleTemplate.get("accessRules", []))
                
                logger.info(f"Created template role '{roleLabel}' with ID {roleId}")
                createdCount += 1
        
        if createdCount > 0:
            logger.info(f"Feature '{FEATURE_CODE}': Created {createdCount} template roles")
        
        return createdCount
        
    except Exception as e:
        logger.error(f"Error syncing template roles for feature '{FEATURE_CODE}': {e}")
        return 0


def _ensureAccessRulesForRole(rootInterface, roleId: str, ruleTemplates: List[Dict[str, Any]]) -> int:
    """
    Ensure AccessRules exist for a role based on templates.
    
    Args:
        rootInterface: Root interface instance
        roleId: Role ID
        ruleTemplates: List of rule templates
        
    Returns:
        Number of rules created
    """
    from modules.datamodels.datamodelRbac import AccessRule, AccessRuleContext
    
    # Get existing rules for this role (Pydantic models)
    existingRules = rootInterface.getAccessRulesByRole(roleId)
    
    # Create a set of existing rule signatures to avoid duplicates
    # IMPORTANT: Use .value for enum comparison, not str() which gives "AccessRuleContext.DATA" in Python 3.11+
    existingSignatures = set()
    for rule in existingRules:
        sig = (rule.context.value if rule.context else None, rule.item)
        existingSignatures.add(sig)
    
    createdCount = 0
    for template in ruleTemplates:
        context = template.get("context", "UI")
        item = template.get("item")
        sig = (context, item)
        
        if sig in existingSignatures:
            continue
        
        # Map context string to enum
        if context == "UI":
            contextEnum = AccessRuleContext.UI
        elif context == "DATA":
            contextEnum = AccessRuleContext.DATA
        elif context == "RESOURCE":
            contextEnum = AccessRuleContext.RESOURCE
        else:
            contextEnum = context
        
        newRule = AccessRule(
            roleId=roleId,
            context=contextEnum,
            item=item,
            view=template.get("view", False),
            read=template.get("read"),
            create=template.get("create"),
            update=template.get("update"),
            delete=template.get("delete"),
        )
        rootInterface.db.recordCreate(AccessRule, newRule.model_dump())
        createdCount += 1
    
    if createdCount > 0:
        logger.debug(f"Created {createdCount} AccessRules for role {roleId}")
    
    return createdCount
