import json
import os
from typing import Any

from .types import Alias, AliasType


def read_json_file(file_name: str) -> dict[str, Any]:
    # Get the directory of the current python script
    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, file_name)
    assert os.path.exists(file_path), f"File not found: {file_path}"

    with open(file_path) as file:
        data = json.load(file)
    return data


def json_to_alias(alias_data: dict[str, Any]) -> Alias:
    address = alias_data["address"]
    detail = alias_data.get("detail", "")

    return Alias(
        name=alias_data["name"],
        alias_type=AliasType(alias_data["type"]),
        description=alias_data.get("descr", ""),
        content=address if isinstance(address, list) else [address],
        detail=detail if isinstance(detail, list) else [detail],
    )


def find_alias_by_name(name: str, aliases: list[Alias]) -> Alias | None:
    for alias in aliases:
        if alias.name == name:
            return alias
    return None


def get_reference_aliases_for_client(client_name: str) -> list[Alias]:
    aliases = read_json_file("../../aliases/aliases.json")
    assert client_name in aliases, f"Client {client_name} not found in aliases.json"

    all_aliases = [json_to_alias(alias) for alias in aliases["all"]]
    client_aliases = [json_to_alias(alias) for alias in aliases[client_name]]

    return all_aliases + client_aliases


def get_exclusions_for_client(client_name: str) -> list[str]:
    excludes = read_json_file("../../aliases/excludes.json")
    return excludes[client_name]["native_subnets"] + excludes[client_name]["excludes"]


def get_ignore_differences_for_client(client_name: str) -> list[str]:
    excludes = read_json_file("../../aliases/excludes.json")
    return excludes[client_name]["ignore_differences"]
