from collections.abc import Callable, Sequence
from typing import Any

from temporalio import activity

from csirtmu.beta_temporal.external_services.alpha.client import AlphaClient
from csirtmu.beta_temporal.external_services.netbox.utils import get_subnet_info_for_ip
from csirtmu.beta_temporal.workflows.logging import LoggedActivities


class AlphaCommonActions(LoggedActivities):
    def __init__(self, alpha_client: AlphaClient) -> None:
        self.alpha_client = alpha_client

    def get_activities(self) -> Sequence[Callable[..., Any]]:
        return [
            self.get_netbox_network_info,
        ]

    @activity.defn
    async def get_netbox_network_info(self, ips: list[str]) -> dict[str, list[str]]:
        self.log_activity()
        if not ips:
            return {}
        networks: set[str] = set()
        subnets: set[str] = set()
        mapping: list[str] = []
        netbox_data = await self.alpha_client.get_ip_address_data(ips)
        for ip in ips:
            if netbox_data is None or (data := get_subnet_info_for_ip(ip, netbox_data.get(ip))) is None:
                network = "Outside / Unknown"
                subnet = "Unknown"
            else:
                subnet = data.tenant[0].name if len(data.tenant) > 0 else "---"
                if "vpn" in subnet.lower() or "vpn" in data.description.lower():
                    network = "vpn"
                elif "eduroam" in subnet.lower() or "eduroam" in data.description.lower():
                    network = "eduroam"
                else:
                    network = "University"
            networks.add(network)
            subnets.add(subnet)
            mapping.append(f"IP: {ip},\tNetwork: {network},\tDepartment: {subnet}")
        return {"Networks": list(networks), "Departments": list(subnets), "IP Mapping": mapping}
