from . import models
from . import exceptions
from .constant import ALL_OBJECTS_TYPE
from typing import Tuple
from urllib.parse import urlencode

def build_optional_query_params(data: dict[str, str]) -> str:
    params = {}
    for k, v in data.items():
        if v:
            params[k] = v
    return urlencode(params)

def find_attribute(attrs: models.Attributes, name: str) -> models.Attribute | None:
    if attrs.attribute:
        for attr in attrs.attribute:
            if attr.name == name:
                return attr
    return None

def get_lookup_key_from_attributes(attrs: models.Attributes) -> Tuple[str, str]:
    obj_type = ""
    lookup_key = ""

    if not attrs.attribute:
        raise exceptions.RipeRestApiInvalidPrimaryKeyError()
    
    for attr in attrs.attribute:
        if attr.name in ALL_OBJECTS_TYPE:
            obj_type = attr.name
            lookup_key = f"{attr.value}"
            break
    
    if not obj_type:
        raise exceptions.RipeRestApiInvalidPrimaryKeyError()
    
    if obj_type == "route" or obj_type == "route6":
        origin = find_attribute(attrs, "origin")
        if not origin:
            raise exceptions.RipeRestApiInvalidPrimaryKeyError()
        lookup_key = f"{lookup_key}{origin.value}"
    
    return (obj_type, lookup_key)
