"""Plugin management API endpoints."""
from typing import List, Dict, Any, Optional
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from ..managers.plugin_manager import get_plugin_manager


router = APIRouter()


class PluginMetadataResponse(BaseModel):
    """Plugin metadata response model."""
    id: str
    name: str
    version: str
    description: str
    author: str
    homepage: Optional[str] = None
    dependencies: List[str] = []
    permissions: List[str] = []


class PluginInfoResponse(BaseModel):
    """Plugin info response model."""
    metadata: PluginMetadataResponse
    status: str
    enabled: bool
    error_message: Optional[str] = None


class PluginActionRequest(BaseModel):
    """Request model for plugin actions."""
    plugin_id: str


@router.get("/discover")
async def discover_plugins():
    """Discover all available plugins.

    Returns:
        List of discovered plugin IDs
    """
    try:
        manager = get_plugin_manager()
        discovered = await manager.discover_plugins()

        return {
            "success": True,
            "plugins": discovered,
            "count": len(discovered)
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/list", response_model=List[PluginInfoResponse])
async def list_plugins():
    """Get list of all plugins.

    Returns:
        List of plugin information
    """
    try:
        manager = get_plugin_manager()
        plugins = manager.get_all_plugins()

        result = []
        for plugin_id, plugin_info in plugins.items():
            result.append(PluginInfoResponse(
                metadata=PluginMetadataResponse(
                    id=plugin_info.metadata.id,
                    name=plugin_info.metadata.name,
                    version=plugin_info.metadata.version,
                    description=plugin_info.metadata.description,
                    author=plugin_info.metadata.author,
                    homepage=plugin_info.metadata.homepage,
                    dependencies=plugin_info.metadata.dependencies,
                    permissions=plugin_info.metadata.permissions
                ),
                status=plugin_info.status.value,
                enabled=plugin_info.enabled,
                error_message=plugin_info.error_message
            ))

        return result

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/{plugin_id}", response_model=PluginInfoResponse)
async def get_plugin_info(plugin_id: str):
    """Get information about a specific plugin.

    Args:
        plugin_id: ID of the plugin

    Returns:
        Plugin information
    """
    try:
        manager = get_plugin_manager()
        plugin_info = manager.get_plugin_info(plugin_id)

        if not plugin_info:
            raise HTTPException(status_code=404, detail="Plugin not found")

        return PluginInfoResponse(
            metadata=PluginMetadataResponse(
                id=plugin_info.metadata.id,
                name=plugin_info.metadata.name,
                version=plugin_info.metadata.version,
                description=plugin_info.metadata.description,
                author=plugin_info.metadata.author,
                homepage=plugin_info.metadata.homepage,
                dependencies=plugin_info.metadata.dependencies,
                permissions=plugin_info.metadata.permissions
            ),
            status=plugin_info.status.value,
            enabled=plugin_info.enabled,
            error_message=plugin_info.error_message
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/enable")
async def enable_plugin(request: PluginActionRequest):
    """Enable a plugin.

    Args:
        request: Plugin action request with plugin_id

    Returns:
        Success message
    """
    try:
        manager = get_plugin_manager()
        success = await manager.enable_plugin(request.plugin_id)

        if not success:
            raise HTTPException(status_code=500, detail="Failed to enable plugin")

        return {
            "success": True,
            "message": f"Plugin {request.plugin_id} enabled"
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/disable")
async def disable_plugin(request: PluginActionRequest):
    """Disable a plugin.

    Args:
        request: Plugin action request with plugin_id

    Returns:
        Success message
    """
    try:
        manager = get_plugin_manager()
        success = await manager.disable_plugin(request.plugin_id)

        if not success:
            raise HTTPException(status_code=500, detail="Failed to disable plugin")

        return {
            "success": True,
            "message": f"Plugin {request.plugin_id} disabled"
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/load")
async def load_plugin(request: PluginActionRequest):
    """Load a plugin into memory.

    Args:
        request: Plugin action request with plugin_id

    Returns:
        Success message
    """
    try:
        manager = get_plugin_manager()
        success = await manager.load_plugin(request.plugin_id)

        if not success:
            raise HTTPException(status_code=500, detail="Failed to load plugin")

        return {
            "success": True,
            "message": f"Plugin {request.plugin_id} loaded"
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/unload")
async def unload_plugin(request: PluginActionRequest):
    """Unload a plugin from memory.

    Args:
        request: Plugin action request with plugin_id

    Returns:
        Success message
    """
    try:
        manager = get_plugin_manager()
        success = await manager.unload_plugin(request.plugin_id)

        if not success:
            raise HTTPException(status_code=500, detail="Failed to unload plugin")

        return {
            "success": True,
            "message": f"Plugin {request.plugin_id} unloaded"
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
