# BFH Science Self-Service Portal
# Copyright (C) 2025-2026 IKUS Software
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from collections import namedtuple

import cherrypy

from bfh_science_ssp.core.const import LNI_INFRASTRUCTURE
from bfh_science_ssp.core.user import User

Infra = namedtuple(
    'Infra', 'name,infra_type,permission,owners,group,manage_url,service', defaults=(LNI_INFRASTRUCTURE,)
)


class InfraHandler:
    """
    Handler for infrastructure card.
    """

    @cherrypy.expose()
    @cherrypy.tools.allow(methods=['GET'])
    @cherrypy.tools.json_out()
    def infra_json(self, u=None, **kwargs):
        """
        Return list of infrastructure resources for Datatable.
        """
        # Query user's attributes
        user = self._query__user(u)
        # Query user's storage

        # Read groups name to find infra:
        # cn=IDM.infra.datacenter.bad9.users,ou=Security,ou=Groups,dc=bfh
        # cn=IDM.infra.<infra_type>.<name>.<permissions>,ou=Security,ou=Groups,dc=bfh
        infras = []
        for group_cn, name, permission in user.deduplicate_groups(
            "cn=IDM.infra.infrastructure.<NAME>.<PERMISSION>,ou=Security,ou=Groups,dc=bfh",
            permission_priority=['admin', 'users'],
        ):

            # Get list of managers for this infra (admin & users)
            groups_dn = [
                f"cn=IDM.infra.infrastructure.{name}.admin,ou=Security,ou=Groups,dc=bfh",
                f"cn=IDM.infra.infrastructure.{name}.users,ou=Security,ou=Groups,dc=bfh",
            ]
            managers = User._query_managers(*groups_dn)
            owners = [manager.as_owner_dict() for manager in managers]

            # Provide manage_url if current user is manager.
            manage_url = None
            currentuser = cherrypy.serving.request.currentuser
            is_owner = any(True for manager in managers if currentuser.username == manager.username)
            manage_url = f"https://idm.bfh.ch/group/{group_cn}" if is_owner else None

            infras.append(
                Infra(
                    name=name,
                    infra_type='infrastructure',
                    permission=permission,
                    owners=owners,
                    group=group_cn,
                    manage_url=manage_url,
                )
            )

        # Return a sorted list
        sorted_infras = sorted(infras, key=lambda x: x.name)
        return {'data': [infra._asdict() for infra in sorted_infras]}
