"""
MCP Integration Layer for DSS Context Compiler
Provides MCP-compliant tool wrappers for the 5 new context tools.
"""

from typing import Dict, Any
import json
from . import (
    get_active_context,
    resolve_token,
    validate_manifest,
    list_skins,
    get_compiler_status
)

# MCP Tool Definitions

def mcp_get_resolved_context(manifest_path: str, debug: bool = False, force_refresh: bool = False) -> str:
    """
    MCP Tool: Get Active Context

    Returns the fully resolved JSON context for a project.
    Set debug=True to see provenance (which layer defined which token).
    Set force_refresh=True to bypass cache (for long-running servers).

    Args:
        manifest_path: Path to ds.config.json
        debug: Enable debug provenance tracking
        force_refresh: Bypass cache and recompile

    Returns:
        JSON string with resolved context
    """
    try:
        return get_active_context(manifest_path, debug, force_refresh)
    except Exception as e:
        return json.dumps({"error": str(e), "status": "failed"})


def mcp_resolve_token(manifest_path: str, token_path: str, force_refresh: bool = False) -> str:
    """
    MCP Tool: Resolve Token

    Resolves a specific token value (e.g. 'colors.primary') through the cascade.
    Set force_refresh=True to bypass cache (for long-running servers).

    Args:
        manifest_path: Path to ds.config.json
        token_path: Dot-notation path to token (e.g. 'colors.primary')
        force_refresh: Bypass cache and recompile

    Returns:
        Resolved token value or error message
    """
    try:
        return resolve_token(manifest_path, token_path, force_refresh)
    except Exception as e:
        return f"Error resolving token: {str(e)}"


def mcp_validate_manifest(manifest_path: str) -> str:
    """
    MCP Tool: Validate Manifest

    Validates the ds.config.json against the schema.

    Args:
        manifest_path: Path to ds.config.json

    Returns:
        Validation result message
    """
    try:
        return validate_manifest(manifest_path)
    except Exception as e:
        return f"Validation error: {str(e)}"


def mcp_list_skins() -> str:
    """
    MCP Tool: List Skins

    Lists all available skins in the registry.

    Returns:
        JSON array of skin IDs
    """
    try:
        return list_skins()
    except Exception as e:
        return json.dumps({"error": str(e), "skins": []})


def mcp_get_compiler_status() -> str:
    """
    MCP Tool: Get Compiler Status

    Returns the health and configuration of the Context Compiler.

    Returns:
        JSON object with compiler status
    """
    try:
        return get_compiler_status()
    except Exception as e:
        return json.dumps({"error": str(e), "status": "error"})


# MCP Tool Registry
# This can be imported by dss-mcp-server.py to register the tools

MCP_TOOLS = {
    "dss_get_resolved_context": {
        "function": mcp_get_resolved_context,
        "description": "Get fully resolved design system context for a project",
        "parameters": {
            "manifest_path": {
                "type": "string",
                "description": "Path to ds.config.json",
                "required": True
            },
            "debug": {
                "type": "boolean",
                "description": "Enable debug provenance tracking",
                "required": False,
                "default": False
            }
        }
    },
    "dss_resolve_token": {
        "function": mcp_resolve_token,
        "description": "Resolve a specific design token through the cascade",
        "parameters": {
            "manifest_path": {
                "type": "string",
                "description": "Path to ds.config.json",
                "required": True
            },
            "token_path": {
                "type": "string",
                "description": "Dot-notation path to token (e.g. 'colors.primary')",
                "required": True
            }
        }
    },
    "dss_validate_manifest": {
        "function": mcp_validate_manifest,
        "description": "Validate project manifest against schema",
        "parameters": {
            "manifest_path": {
                "type": "string",
                "description": "Path to ds.config.json",
                "required": True
            }
        }
    },
    "dss_list_skins": {
        "function": mcp_list_skins,
        "description": "List all available design system skins",
        "parameters": {}
    },
    "dss_get_compiler_status": {
        "function": mcp_get_compiler_status,
        "description": "Get Context Compiler health and configuration",
        "parameters": {}
    }
}
