from __future__ import annotations

from typing import Any

from ..spec_models import NavigationItemSpec, NavigationTargetType, SolutionSpec
from .icon_utils import normalize_workspace_icon_name


def compile_navigation(spec: SolutionSpec) -> list[dict[str, Any]]:
    if not spec.preferences.create_navigation or not spec.navigation.enabled:
        return []
    compiled_items = [_compile_item(item) for item in spec.navigation.items]
    if not compiled_items:
        return []
    package_item = next(
        (
            item
            for item in compiled_items
            if item["payload"].get("targetType") == "TAG"
        ),
        None,
    )
    if package_item is None:
        return compiled_items[:1]
    package_item["children"] = []
    return [package_item]


def _compile_item(item: NavigationItemSpec) -> dict[str, Any]:
    default_icon = _default_navigation_icon(item.target_type)
    payload: dict[str, Any] = {
        "item_id": item.item_id,
        "payload": {
            "name": item.title,
            "navigationIcon": normalize_workspace_icon_name(item.icon or default_icon) or default_icon,
            "auth": {"type": "WORKSPACE"},
            **item.config,
        },
        "children": [_compile_item(child) for child in item.children],
    }
    if item.target_type == NavigationTargetType.package:
        payload["payload"].update({"targetType": "TAG", "tagId": "__PACKAGE_TAG_ID__"})
    elif item.target_type == NavigationTargetType.app:
        payload["payload"].update({"targetType": "APP", "appRef": {"entity_id": item.entity_id}})
    elif item.target_type == NavigationTargetType.portal:
        payload["payload"].update({"targetType": "DASH", "dashKey": "__PORTAL_DASH_KEY__"})
    else:
        raise ValueError("navigation target_type currently supports only: package, app, portal")
    return payload


def _default_navigation_icon(target_type: NavigationTargetType) -> str:
    if target_type == NavigationTargetType.package:
        return "ex-folder-outlined"
    if target_type == NavigationTargetType.portal:
        return "ex-home-outlined"
    return "ex-form-outlined"
