from flask import session, current_app
from sqlalchemy import and_

from common.models.user import Tenant, Partner
from common.models.entitlements import License
from common.utils.database import Database
from common.utils.eveai_exceptions import EveAITenantNotFound, EveAITenantInvalid, EveAINoActiveLicense
from datetime import datetime as dt, timezone as tz
from common.services.user import TenantServices


# Definition of Trigger Handlers
def set_tenant_session_data(sender, user, **kwargs):
    tenant = Tenant.query.filter_by(id=user.tenant_id).first()
    session['tenant'] = tenant.to_dict()
    partner = Partner.query.filter_by(tenant_id=user.tenant_id).first()
    if partner:
        session['partner'] = partner.to_dict()
    else:
        # Remove partner from session if it exists
        session.pop('partner', None)

    session['consent_status'] = str(TenantServices.get_consent_status(user.tenant_id))


def clear_tenant_session_data(sender, user, **kwargs):
    session.pop('tenant', None)
    session.pop('default_language', None)
    session.pop('default_llm_model', None)
    session.pop('partner', None)
    session.pop('consent_status', None)


def is_valid_tenant(tenant_id):
    if tenant_id == 1:  # The 'root' tenant, is always valid
        return True
    tenant = Tenant.query.get(tenant_id)
    Database(tenant).switch_schema()
    if tenant is None:
        raise EveAITenantNotFound()
    elif tenant.type == 'Inactive':
        raise EveAITenantInvalid(tenant_id)
    else:
        current_date = dt.now(tz=tz.utc).date()
        # TODO -> Check vervangen door Active License Period!
        # active_license = (License.query.filter_by(tenant_id=tenant_id)
        #                   .filter(and_(License.start_date <= current_date,
        #                                License.end_date >= current_date))
        #                   .one_or_none())
        # if not active_license:
        #     raise EveAINoActiveLicense(tenant_id)

    return True
