"""FCP-specific constants and configuration values.

This module centralizes all FCP-specific constants to improve maintainability
and make it easier to update provider-specific values.

All API constants, enums, and validated values from the FCP OpenAPI specification
are defined here to avoid hardcoding throughout the codebase.
"""

import os
from enum import Enum
from typing import Any, Dict, List

# ==================== Regions ====================
VALID_REGIONS: List[str] = [
    "eu-central1-a",
    "na-east1-a",
    "na-east1-b",
    "us-central1-a",
    "us-central1-b",
]

# Startup Script Limits
# FCP has a 10,000 character limit for uncompressed startup scripts
# Source: https://docs.mlfoundry.com/compute-and-storage/startup-scripts
STARTUP_SCRIPT_MAX_SIZE = 10 * 1000  # 10,000 characters

# Log Locations
# FCP expects logs at specific locations for compatibility
FCP_LOG_DIR = os.getenv("FCP_LOG_DIR", "/var/log/foundry")
FCP_STARTUP_LOG = f"{FCP_LOG_DIR}/startup_script.log"

# Flow's internal log locations
FLOW_LOG_DIR = os.getenv("FLOW_LOG_DIR", "/var/log/flow")
FLOW_LEGACY_LOG_DIR = os.getenv("FLOW_LEGACY_LOG_DIR", "/var/log/fcp")  # For backward compatibility

# ==================== Storage ====================
# Disk interface types from FCP API
# Note: UI shows "File share" but API expects "File"
DISK_INTERFACE_BLOCK = "Block"
DISK_INTERFACE_FILE = "File"

VALID_DISK_INTERFACES = [DISK_INTERFACE_BLOCK, DISK_INTERFACE_FILE]

# ==================== Instance Status ====================
class InstanceStatus(str, Enum):
    """Instance lifecycle statuses from API."""

    PENDING = "STATUS_PENDING"
    NEW = "STATUS_NEW"
    CONFIRMED = "STATUS_CONFIRMED"
    SCHEDULED = "STATUS_SCHEDULED"
    INITIALIZING = "STATUS_INITIALIZING"
    STARTING = "STATUS_STARTING"
    RUNNING = "STATUS_RUNNING"
    STOPPING = "STATUS_STOPPING"
    STOPPED = "STATUS_STOPPED"
    TERMINATED = "STATUS_TERMINATED"
    RELOCATING = "STATUS_RELOCATING"
    PREEMPTING = "STATUS_PREEMPTING"
    PREEMPTED = "STATUS_PREEMPTED"
    REPLACED = "STATUS_REPLACED"

# ==================== Bid Status ====================
class BidStatus(str, Enum):
    """Bid/Task statuses from API."""

    OPEN = "Open"
    ALLOCATED = "Allocated"
    PREEMPTING = "Preempting"
    TERMINATED = "Terminated"

# ==================== Order Types ====================
class OrderType(str, Enum):
    """Types of orders in FCP."""

    BID = "Bid"
    RESERVATION = "Reservation"

# ==================== Sort Options ====================
class SortDirection(str, Enum):
    """Sort directions for API queries."""

    ASC = "asc"
    DESC = "desc"

# Instance Type Mappings
# These FIDs are from the actual FCP API as of 2025-07-02
INSTANCE_TYPE_MAPPINGS = {
    # A100 mappings
    "a100": "it_MsIRhxj3ccyVWGfP",  # Default to 1x
    "1xa100": "it_MsIRhxj3ccyVWGfP",
    "2xa100": "it_5M6aGxGovNeX5ltT",
    "4xa100": "it_fK7Cx6TVhOK5ZfXT",
    "8xa100": "it_J7OyNf9idfImLIFo",
    # FCP format also supported
    "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",  # Default to 8x
    "8xh100": "it_5ECSoHQjLBzrp5YM",
    "h100-80gb.sxm.8x": "it_5ECSoHQjLBzrp5YM",
    "h100-80gb.pcie.1x": "it_XqgKWbhZ5gznAYsG",  # Different FID for PCIe
}

# Reverse mapping for display purposes
INSTANCE_TYPE_NAMES = {
    "it_MsIRhxj3ccyVWGfP": "a100-80gb.sxm.1x",
    "it_5M6aGxGovNeX5ltT": "a100-80gb.sxm.2x",
    "it_fK7Cx6TVhOK5ZfXT": "a100-80gb.sxm.4x",
    "it_J7OyNf9idfImLIFo": "a100-80gb.sxm.8x",
    "it_5ECSoHQjLBzrp5YM": "h100-80gb.sxm.8x",
    "it_XqgKWbhZ5gznAYsG": "h100-80gb.pcie.1x",
}

# API Endpoints
import os

FCP_API_BASE_URL = os.getenv("FCP_API_URL", "https://api.mlfoundry.com")
FCP_API_VERSION = "v2"
FCP_WEB_BASE_URL = os.getenv("FCP_WEB_URL", "https://app.mlfoundry.com")
FCP_DOCS_URL = os.getenv("FCP_DOCS_URL", "https://docs.mlfoundry.com")
FCP_STATUS_URL = os.getenv("FCP_STATUS_URL", "https://status.mlfoundry.com")

# Resource Limits
MAX_VOLUMES_PER_INSTANCE = 20  # AWS limit that FCP inherits
MAX_INSTANCES_PER_TASK = 256
MAX_VOLUME_SIZE_GB = 16384  # 16TB

# Timeouts
DEFAULT_HTTP_TIMEOUT = 30  # seconds
VOLUME_DELETE_TIMEOUT = 120  # seconds, volume deletion can be slow

# User Cache
USER_CACHE_TTL = 3600  # 1 hour TTL for user information cache

# SSH Configuration
DEFAULT_SSH_USER = os.getenv("FCP_SSH_USER", "ubuntu")
DEFAULT_SSH_PORT = int(os.getenv("FCP_SSH_PORT", "22"))

# Volume Configuration
VOLUME_ID_PREFIX = "vol_"

# Status Mappings
# Map FCP status strings to TaskStatus enum values
STATUS_MAPPINGS = {
    "pending": "PENDING",
    "provisioning": "PENDING",  # Still waiting for allocation
    "allocated": "RUNNING",  # FCP uses "Allocated" for running instances
    "running": "RUNNING",
    "completed": "COMPLETED",
    "failed": "FAILED",
    "cancelled": "CANCELLED",
    "terminated": "CANCELLED",
}

# Supported Regions
SUPPORTED_REGIONS = [
    "us-central-1",
    "us-central-2",
    "us-central-3",
    "us-east-1",
    "us-east-2",
    "us-east-3",
    "us-south-1",
    "us-south-2",
    "us-south-3",
    "us-west-1",
    "us-west-2",
    "us-west-3",
    "australia-1",
    "europe-1",
    "asia-1",
]

# Default Region
DEFAULT_REGION = os.getenv("FCP_DEFAULT_REGION", "us-central1-a")

# ==================== Instance Types ====================
# Note: These should be fetched dynamically from /v2/instance-types
# This is just for reference/examples
EXAMPLE_INSTANCE_TYPES = [
    "h100.80gb.sxm",
    "a100.80gb.sxm",
    "a40.48gb.pcie",
]

# ==================== API Defaults ====================
DEFAULT_DISK_INTERFACE = DISK_INTERFACE_BLOCK

# ==================== Validation Messages ====================
# Centralized validation help messages
VALIDATION_MESSAGES = {
    "region": {
        "help": "Valid regions",
        "examples": VALID_REGIONS,
        "note": "Additional regions may be available. Check FCP documentation.",
    },
    "disk_interface": {
        "help": "Valid disk interfaces",
        "examples": [
            f"{DISK_INTERFACE_BLOCK} (high-performance block storage)",
            f"{DISK_INTERFACE_FILE} (shared file storage)",
        ],
    },
    "instance_type": {
        "help": "Example instance types",
        "examples": [
            "a100-80gb.sxm.4x (4x A100 GPUs)",
            "h100-80gb.sxm.8x (8x H100 GPUs)",
            "t4-16gb.pcie.1x (1x T4 GPU)",
        ],
        "note": "Run 'flow instances' to see all available types",
    },
}


def get_validation_help(field: str) -> Dict[str, Any]:
    """Get validation help message for a field.

    Args:
        field: Field name to get help for

    Returns:
        Dictionary with help, examples, and optional note
    """
    return VALIDATION_MESSAGES.get(field, {})


def format_validation_help(field: str) -> List[str]:
    """Format validation help as list of strings for error messages.

    Args:
        field: Field name to format help for

    Returns:
        List of formatted help strings
    """
    help_info = get_validation_help(field)
    if not help_info:
        return []

    lines = []

    if help_info.get("help"):
        lines.append(f"{help_info['help']}:")

    for example in help_info.get("examples", []):
        lines.append(f"  - {example}")

    if help_info.get("note"):
        if lines:
            lines.append("")
        lines.append(help_info["note"])

    return lines
