from typing import List, Dict, Any

from flask import session
from sqlalchemy.exc import SQLAlchemyError

from common.models.entitlements import PartnerServiceLicenseTier
from common.utils.eveai_exceptions import EveAINoManagementPartnerService, EveAINoSessionPartner



class PartnerServices:
    @staticmethod
    def get_allowed_license_tier_ids() -> List[int]:
        """
        Retrieve IDs of all License Tiers associated with the partner's management service

        Returns:
            List of license tier IDs

        Raises:
            EveAINoSessionPartner: If no partner is in the session
            EveAINoManagementPartnerService: If partner has no management service
        """
        partner = session.get("partner", None)
        if not partner:
            raise EveAINoSessionPartner()

        # Find a management service for this partner
        management_service = next((service for service in session['partner']['services']
                                   if service.get('type') == 'MANAGEMENT_SERVICE'), None)
        if not management_service:
            raise EveAINoManagementPartnerService()
        management_service_id = management_service['id']

        # Query for all license tiers associated with this management service
        associations = PartnerServiceLicenseTier.query.filter_by(
            partner_service_id=management_service_id
        ).all()

        # Extract the license tier IDs
        license_tier_ids = [assoc.license_tier_id for assoc in associations]

        return license_tier_ids

    @staticmethod
    def get_management_service() -> Dict[str, Any]:
        management_service = next((service for service in session['partner']['services']
                                   if service.get('type') == 'MANAGEMENT_SERVICE'), None)
        return management_service



