from flask import redirect, flash, current_app, session, url_for
from flask_security import roles_accepted
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import desc
import ast

from common.models.interaction import Specialist, SpecialistMagicLink, ChatSession, EveAIDataCapsule
from common.utils.nginx_utils import prefixed_url_for
from eveai_app.views.list_views.list_view_utils import render_list_view

# Specialists list view helper
def get_specialists_list_view():
    """Generate the specialists list view configuration"""
    # Get all specialists
    specialists_query = Specialist.query.order_by(Specialist.id)
    all_specialists = specialists_query.all()

    # Prepare data for Tabulator
    data = []
    for specialist in all_specialists:
        data.append({
            'id': specialist.id,
            'name': specialist.name,
            'type': specialist.type,
            'type_version': specialist.type_version,
            'active': specialist.active
        })

    # Column definitions
    columns = [
        {'title': 'ID', 'field': 'id', 'width': 80},
        {'title': 'Name', 'field': 'name'},
        {'title': 'Type', 'field': 'type'},
        {'title': 'Type Version', 'field': 'type_version'},
        {'title': 'Active', 'field': 'active', 'formatter': 'tickCross'}
    ]

    # Action definitions
    actions = [
        {'value': 'edit_specialist', 'text': 'Edit Specialist', 'class': 'btn-primary', 'requiresSelection': True},
        {'value': 'execute_specialist', 'text': 'Execute Specialist', 'class': 'btn-primary', 'requiresSelection': True},
        {'value': 'create_specialist', 'text': 'Register Specialist', 'class': 'btn-success', 'position': 'right', 'requiresSelection': False}
    ]

    # Initial sort configuration
    initial_sort = [{'column': 'id', 'dir': 'asc'}]

    return {
        'title': 'Specialists',
        'data': data,
        'columns': columns,
        'actions': actions,
        'initial_sort': initial_sort,
        'table_id': 'specialists_table',
        'form_action': url_for('interaction_bp.handle_specialist_selection'),
        'description': 'View and manage specialists',
        'table_height': 800  # Hogere tabel voor specialists view
    }


def get_assets_list_view():
    """Generate the assets list view configuration"""
    # Get all assets
    from common.models.interaction import EveAIAsset
    assets_query = EveAIAsset.query.order_by(EveAIAsset.id)
    all_assets = assets_query.all()

    # Prepare data for Tabulator
    data = []
    for asset in all_assets:
        data.append({
            'id': asset.id,
            'name': asset.name,
            'type': asset.type,
            'type_version': asset.type_version,
        })

    # Column definitions
    columns = [
        {'title': 'ID', 'field': 'id', 'width': 80},
        {'title': 'Name', 'field': 'name'},
        {'title': 'Type', 'field': 'type'},
        {'title': 'Type Version', 'field': 'type_version'}
    ]

    # Action definitions
    actions = [
        {'value': 'edit_asset', 'text': 'Edit Asset', 'class': 'btn-primary', 'requiresSelection': True},
        {'value': 'create_asset', 'text': 'Register Asset', 'class': 'btn-success', 'position': 'right', 'requiresSelection': False}
    ]

    # Initial sort configuration
    initial_sort = [{'column': 'id', 'dir': 'asc'}]

    return {
        'title': 'Assets',
        'data': data,
        'columns': columns,
        'actions': actions,
        'initial_sort': initial_sort,
        'table_id': 'assets_table',
        'form_action': url_for('interaction_bp.handle_asset_selection'),
        'description': 'View and manage assets',
        'table_height': 800
    }


def get_magic_links_list_view():
    """Generate the specialist magic links list view configuration"""
    # Get all specialist magic links
    magic_links_query = SpecialistMagicLink.query.order_by(SpecialistMagicLink.id)
    all_magic_links = magic_links_query.all()

    # Prepare data for Tabulator
    data = []
    for magic_link in all_magic_links:
        data.append({
            'id': magic_link.id,
            'name': magic_link.name,
            'magic_link_code': magic_link.magic_link_code,
            'specialist_id': magic_link.specialist_id
        })

    # Column definitions
    columns = [
        {'title': 'ID', 'field': 'id', 'width': 80},
        {'title': 'Name', 'field': 'name'},
        {'title': 'Magic Link Code', 'field': 'magic_link_code'},
        {'title': 'Specialist ID', 'field': 'specialist_id'}
    ]

    # Action definitions
    actions = [
        {'value': 'edit_specialist_magic_link', 'text': 'Edit Magic Link', 'class': 'btn-primary', 'requiresSelection': True},
        {'value': 'view_specialist_magic_link_urls', 'text': 'View Magic Link URLs', 'class': 'btn-secondary', 'requiresSelection': True},
        {'value': 'create_specialist_magic_link', 'text': 'Create Magic Link', 'class': 'btn-success', 'position': 'right', 'requiresSelection': False},
    ]

    # Initial sort configuration
    initial_sort = [{'column': 'id', 'dir': 'asc'}]

    return {
        'title': 'Specialist Magic Links',
        'data': data,
        'columns': columns,
        'actions': actions,
        'initial_sort': initial_sort,
        'table_id': 'specialist_magic_links_table',
        'form_action': url_for('interaction_bp.handle_specialist_magic_link_selection'),
        'description': 'View and manage specialist magic links',
        'table_height': 800
    }


def get_chat_sessions_list_view():
    """Generate the chat sessions list view configuration"""
    # Get all chat sessions ordered by session_start (descending)
    chat_sessions_query = ChatSession.query.order_by(desc(ChatSession.session_start))
    all_chat_sessions = chat_sessions_query.all()

    # Prepare data for Tabulator
    data = []
    for chat_session in all_chat_sessions:
        data.append({
            'id': chat_session.id,
            'session_id': chat_session.session_id,
            'session_start': chat_session.session_start.strftime('%Y-%m-%d %H:%M:%S') if chat_session.session_start else '',
            'session_end': chat_session.session_end.strftime('%Y-%m-%d %H:%M:%S') if chat_session.session_end else '',
        })

    # Column definitions
    columns = [
        {'title': 'ID', 'field': 'id', 'width': 80},
        {'title': 'Session ID', 'field': 'session_id'},
        {'title': 'Start Time', 'field': 'session_start'},
        {'title': 'End Time', 'field': 'session_end'},
    ]

    # Action definitions
    actions = [
        {'value': 'view_chat_session', 'text': 'View Details', 'class': 'btn-primary', 'requiresSelection': True},
        {'value': 'chat_session_interactions', 'text': 'View Interactions', 'class': 'btn-secondary', 'requiresSelection': True}
    ]

    # Initial sort configuration
    initial_sort = [{'column': 'session_start', 'dir': 'desc'}]

    return {
        'title': 'Chat Sessions',
        'data': data,
        'columns': columns,
        'actions': actions,
        'initial_sort': initial_sort,
        'table_id': 'chat_sessions_table',
        'form_action': url_for('interaction_bp.handle_chat_session_selection'),
        'description': 'View all chat sessions',
        'table_height': 800
    }


def get_eveai_data_capsules_list_view():
    """Generate the EvAI Data Capsules list view configuration"""
    # Get all data capsules ordered by creation date (descending)
    data_capsules_query = EveAIDataCapsule.query.order_by(desc(EveAIDataCapsule.created_at))
    all_data_capsules = data_capsules_query.all()

    # Prepare data for Tabulator
    data = []
    for capsule in all_data_capsules:
        data.append({
            'id': capsule.id,
            'chat_session_id': capsule.chat_session_id,
            'type': capsule.type,
            'type_version': capsule.type_version,
            'created_at': capsule.created_at.strftime('%Y-%m-%d %H:%M:%S') if capsule.created_at else ''
        })

    # Column definitions
    columns = [
        {'title': 'ID', 'field': 'id', 'width': 80},
        {'title': 'Chat Session ID', 'field': 'chat_session_id'},
        {'title': 'Type', 'field': 'type'},
        {'title': 'Type Version', 'field': 'type_version'},
        {'title': 'Created At', 'field': 'created_at'}
    ]

    # Action definitions
    actions = [
        {'value': 'view_data_capsule', 'text': 'View Details', 'class': 'btn-primary', 'requiresSelection': True},
        {'value': 'view_chat_session', 'text': 'View Chat Session', 'class': 'btn-secondary', 'requiresSelection': True}
    ]

    # Initial sort configuration
    initial_sort = [{'column': 'created_at', 'dir': 'desc'}]

    return {
        'title': 'EvAI Data Capsules',
        'data': data,
        'columns': columns,
        'actions': actions,
        'initial_sort': initial_sort,
        'table_id': 'eveai_data_capsules_table',
        'form_action': url_for('interaction_bp.handle_data_capsule_selection'),
        'description': 'View all EvAI Data Capsules',
        'table_height': 800
    }

