# Copyright 2025 Foundry Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Instance type resolution via Flow SDK catalog."""

from typing import Dict

# Import Flow SDK catalog with graceful fallback
try:
    from flow.providers.fcp.catalog_resolver import CatalogResolver
    _catalog_resolver = CatalogResolver()
    CATALOG_AVAILABLE = True
except ImportError:
    _catalog_resolver = None
    CATALOG_AVAILABLE = False


class InstanceResolver:
    """Maps instance type identifiers to canonical names."""
    
    def __init__(self):
        """Initialize with empty cache."""
        self._cache: Dict[str, str] = {}
    
    def resolve(self, instance_id: str) -> str:
        """Convert instance type ID to canonical name.
        
        Args:
            instance_id: FCP instance type identifier
            
        Returns:
            Canonical name or original ID if unresolvable
        """
        # Check local cache
        if instance_id in self._cache:
            return self._cache[instance_id]
        
        # Query Flow SDK catalog
        if CATALOG_AVAILABLE and _catalog_resolver:
            instance_type = _catalog_resolver.get_by_id(instance_id)
            if instance_type:
                self._cache[instance_id] = instance_type.name
                return instance_type.name
        
        # Fallback to raw ID
        return instance_id
    
    def populate_from_api(self, instance_types: list) -> None:
        """Update cache with API-provided mappings.
        
        Args:
            instance_types: API response containing type metadata
        """
        for it in instance_types:
            fid = it.get("fid")
            name = it.get("name")
            if fid and name:
                self._cache[fid] = name


# Singleton resolver
resolver = InstanceResolver()