"""FCP Instance Type Configuration.

This module provides a flexible system for mapping user-friendly instance type
names to provider-specific IDs. It supports loading mappings from:
1. Environment variables
2. Configuration files  
3. Built-in defaults

This allows the SDK to work with different providers without hardcoding
instance type IDs in the source code.
"""

import json
import os
from pathlib import Path
from typing import Dict


class InstanceTypeMapper:
    """Maps user-friendly instance names to provider-specific IDs."""

    def __init__(self):
        self._mappings: Dict[str, str] = {}
        self._reverse_mappings: Dict[str, str] = {}
        self._load_mappings()

    def _load_mappings(self):
        """Load instance type mappings from various sources."""
        # 1. Start with built-in defaults (can be empty for OSS)
        self._mappings = self._get_default_mappings()

        # 2. Load from config file if exists
        config_path = Path.home() / ".flow" / "instance_types.json"
        if config_path.exists():
            try:
                with open(config_path) as f:
                    file_mappings = json.load(f)
                    self._mappings.update(file_mappings)
            except Exception:
                pass

        # 3. Override with environment variable if set
        env_mappings = os.getenv("FCP_INSTANCE_MAPPINGS")
        if env_mappings:
            try:
                env_dict = json.loads(env_mappings)
                self._mappings.update(env_dict)
            except Exception:
                pass

        # Build reverse mappings
        self._reverse_mappings = {v: k for k, v in self._mappings.items()}

    def _get_default_mappings(self) -> Dict[str, str]:
        """Get default mappings.

        For OSS, these can be empty - users will need to configure
        their own mappings via environment or config file.
        """
        # Check if we should include defaults
        if os.getenv("FCP_INCLUDE_DEFAULT_MAPPINGS", "false").lower() == "true":
            return {
                # A100 mappings
                "a100": "it_MsIRhxj3ccyVWGfP",
                "1xa100": "it_MsIRhxj3ccyVWGfP",
                "2xa100": "it_5M6aGxGovNeX5ltT",
                "4xa100": "it_fK7Cx6TVhOK5ZfXT",
                "8xa100": "it_J7OyNf9idfImLIFo",
                "a100-80gb.sxm.1x": "it_MsIRhxj3ccyVWGfP",
                "a100-80gb.sxm.2x": "it_5M6aGxGovNeX5ltT",
                "a100-80gb.sxm.4x": "it_fK7Cx6TVhOK5ZfXT",
                "a100-80gb.sxm.8x": "it_J7OyNf9idfImLIFo",
                # H100 mappings
                "h100": "it_5ECSoHQjLBzrp5YM",
                "8xh100": "it_5ECSoHQjLBzrp5YM",
                "h100-80gb.sxm.8x": "it_5ECSoHQjLBzrp5YM",
                "h100-80gb.pcie.1x": "it_XqgKWbhZ5gznAYsG",
            }
        return {}

    def resolve(self, instance_type: str) -> str:
        """Resolve user-friendly name to provider ID.

        Args:
            instance_type: User-friendly instance type name

        Returns:
            Provider-specific instance ID

        Raises:
            ValueError: If instance type is unknown
        """
        # Direct ID passthrough
        if instance_type.startswith("it_"):
            return instance_type

        # Look up in mappings
        instance_id = self._mappings.get(instance_type)
        if not instance_id:
            available = list(self._mappings.keys())
            if available:
                raise ValueError(
                    f"Unknown instance type: {instance_type}. "
                    f"Available: {', '.join(sorted(available))}"
                )
            else:
                raise ValueError(
                    "No instance type mappings configured. "
                    "Set FCP_INSTANCE_MAPPINGS environment variable or "
                    "create ~/.flow/instance_types.json"
                )

        return instance_id

    def get_display_name(self, instance_id: str) -> str:
        """Get display name for instance ID.

        Args:
            instance_id: Provider-specific instance ID

        Returns:
            User-friendly display name
        """
        return self._reverse_mappings.get(instance_id, instance_id)


# Global instance
_mapper = InstanceTypeMapper()


def resolve_instance_type(instance_type: str) -> str:
    """Resolve user-friendly instance type to provider ID."""
    return _mapper.resolve(instance_type)


def get_instance_display_name(instance_id: str) -> str:
    """Get display name for instance ID."""
    return _mapper.get_display_name(instance_id)
