from flask import url_for, current_app, session
from datetime import datetime as dt, timezone as tz
from flask import flash
from sqlalchemy import or_, desc

from common.models.entitlements import LicenseTier, License, LicensePeriod
from common.services.user import PartnerServices, UserServices
from common.utils.eveai_exceptions import EveAIException
from common.utils.security_utils import current_user_has_role


def get_license_tiers_list_view():
    """Generate the license tiers list view configuration"""
    today = dt.now(tz.utc)

    # Build the query
    query = LicenseTier.query.filter(
        or_(
            LicenseTier.end_date == None,
            LicenseTier.end_date >= today
        )
    )

    # Apply partner-specific filtering if needed
    if current_user_has_role('Partner Admin'):
        try:
            license_tier_ids = PartnerServices.get_allowed_license_tier_ids()
        except EveAIException as e:
            flash(f"Cannot retrieve License Tiers: {str(e)}", 'danger')
            current_app.logger.error(f'Cannot retrieve License Tiers for partner: {str(e)}')
            return {
                'title': 'License Tiers',
                'data': [],
                'columns': [],
                'actions': [],
                'initial_sort': [],
                'table_id': 'license_tiers_table',
                'form_action': url_for('entitlements_bp.handle_license_tier_selection'),
                'description': 'View and manage license tiers',
                'table_height': 700,
                'error': True
            }

        if license_tier_ids and len(license_tier_ids) > 0:
            query = query.filter(LicenseTier.id.in_(license_tier_ids))

    # Order the results
    query = query.order_by(LicenseTier.start_date.desc(), LicenseTier.id)

    # Get all license tiers
    license_tiers = query.all()

    # Prepare data for Tabulator
    data = []
    for tier in license_tiers:
        data.append({
            'id': tier.id,
            'name': tier.name,
            'version': tier.version,
            'start_date': tier.start_date.strftime('%Y-%m-%d') if tier.start_date else '',
            'end_date': tier.end_date.strftime('%Y-%m-%d') if tier.end_date else ''
        })

    # Column definitions
    columns = [
        {'title': 'ID', 'field': 'id', 'width': 80, 'type': 'number'},
        {'title': 'Name', 'field': 'name'},
        {'title': 'Version', 'field': 'version', 'width': 120},
        {'title': 'Start Date', 'field': 'start_date', 'width': 120},
        {'title': 'End Date', 'field': 'end_date', 'width': 120}
    ]

    # Action definitions
    actions = [
        {'value': 'edit_license_tier', 'text': 'Edit License Tier', 'class': 'btn-primary', 'requiresSelection': True},
        {'value': 'create_license_tier', 'text': 'Create License Tier', 'class': 'btn-secondary', 'position': 'right',
         'requiresSelection': False}
    ]

    # Add assign license actions if user has permission
    current_app.logger.debug(f"Adding specific buttons")
    if UserServices.can_user_assign_license():
        current_app.logger.debug(f"Adding Create License for Tenant")
        actions.insert(1, {'value': 'create_license_for_tenant', 'text': 'Create License for Tenant',
                           'class': 'btn-secondary', 'requiresSelection': True})
    if current_user_has_role('Super User'):
        current_app.logger.debug(f"Adding Associate License Tier to Partner")
        actions.insert(2, {'value': 'associate_license_tier_to_partner', 'text': 'Associate License Tier to Partner',
                           'class': 'btn-secondary','requiresSelection': True})

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

    return {
        'title': 'License Tiers',
        'data': data,
        'columns': columns,
        'actions': actions,
        'initial_sort': initial_sort,
        'table_id': 'license_tiers_table',
        'form_action': url_for('entitlements_bp.handle_license_tier_selection'),
        'description': 'View and manage license tiers',
        'table_height': 700
    }


def get_license_list_view():
    """Generate the licenses list view configuration"""
    tenant_id = session.get('tenant').get('id')
    # Get current date in UTC
    current_date = dt.now(tz=tz.utc).date()

    # Query licenses for the tenant, with ordering and active status
    query = (
        License.query
        .join(LicenseTier)  # Join with LicenseTier
        .filter(License.tenant_id == tenant_id)
        .add_columns(
            License.id,
            License.start_date,
            License.nr_of_periods,
            LicenseTier.name.label('license_tier_name'),  # Access name through LicenseTier
            (License.start_date <= current_date).label('active')
        )
        .order_by(License.start_date.desc())
    )

    # Get all licenses
    licenses_list = query.all()

    # Prepare data for Tabulator
    data = []
    for license in licenses_list:
        data.append({
            'id': license.id,
            'license_tier_name': license.license_tier_name,
            'start_date': license.start_date.strftime('%Y-%m-%d') if license.start_date else '',
            'nr_of_periods': license.nr_of_periods,
            'active': license.active
        })

    # Column definitions
    columns = [
        {'title': 'ID', 'field': 'id', 'width': 80, 'type': 'number'},
        {'title': 'License Tier', 'field': 'license_tier_name'},
        {'title': 'Start Date', 'field': 'start_date', 'width': 120},
        {'title': 'Nr of Periods', 'field': 'nr_of_periods', 'width': 120},
        {'title': 'Active', 'field': 'active', 'formatter': 'tickCross', 'width': 80}
    ]

    # Action definitions
    actions = [
        {'value': 'edit_license', 'text': 'Edit License', 'class': 'btn-primary', 'requiresSelection': True},
        {'value': 'view_periods', 'text': 'View Periods', 'class': 'btn-secondary', 'requiresSelection': True}
    ]

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

    return {
        'title': 'Licenses', 
        'data': data, 
        'columns': columns, 
        'actions': actions, 
        'initial_sort': initial_sort, 
        'table_id': 'licenses_table',
        'form_action': url_for('entitlements_bp.handle_license_selection'),
        'description': 'View and manage licenses',
        'table_height': 700
    }


def get_license_periods_list_view(license_id):
    """Generate the license periods list view configuration"""
    # Get the license object
    license = License.query.get_or_404(license_id)

    # Get all periods for this license
    periods = (LicensePeriod.query
              .filter_by(license_id=license_id)
              .order_by(LicensePeriod.period_number)
              .all())

    # Prepare data for Tabulator
    data = []
    for period in periods:
        # Get usage data
        usage = period.license_usage
        storage_used = usage.storage_mb_used if usage else 0
        embedding_used = usage.embedding_mb_used if usage else 0
        interaction_used = usage.interaction_total_tokens_used if usage else 0

        # Get payment status
        prepaid_payment = period.prepaid_payment
        prepaid_status = prepaid_payment.status.name if prepaid_payment else 'N/A'

        # Get invoice status
        prepaid_invoice = period.prepaid_invoice
        invoice_status = prepaid_invoice.status.name if prepaid_invoice else 'N/A'

        data.append({
            'id': period.id,
            'period_number': period.period_number,
            'period_start': period.period_start.strftime('%Y-%m-%d'),
            'period_end': period.period_end.strftime('%Y-%m-%d'),
            'status': period.status.name,
        })

    # Column definitions
    columns = [
        {'title': 'ID', 'field': 'id', 'width': 60, 'type': 'number'},
        {'title': 'Period', 'field': 'period_number'},
        {'title': 'Start Date', 'field': 'period_start'},
        {'title': 'End Date', 'field': 'period_end'},
        {'title': 'Status', 'field': 'status'},
    ]

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

    # If user has admin roles, add transition action
    if current_user_has_role('Super User'):
        actions.append({'value': 'edit_license_period', 'text': 'Edit Period', 'class': 'btn-secondary', 'requiresSelection': True})

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

    return {
        'title': 'License Periods',
        'data': data,
        'columns': columns,
        'actions': actions,
        'initial_sort': initial_sort,
        'table_id': 'license_periods_table',
        'form_action': url_for('entitlements_bp.handle_license_period_selection', license_id=license_id),
        'description': f'View and manage periods for License {license_id}',
        'table_height': 700,
        'license': license
    }
