"""Plugin management API — list, enable, disable, reload."""

from __future__ import annotations

from fastapi import APIRouter, Request

router = APIRouter(prefix="/plugins", tags=["plugins"])


@router.get("")
async def list_plugins(request: Request) -> dict:
    pm = request.app.state.plugin_manager
    return {"plugins": pm.list_plugins()}


@router.get("/{name}")
async def get_plugin(request: Request, name: str) -> dict:
    pm = request.app.state.plugin_manager
    plugin = pm.get_plugin(name)
    if not plugin:
        return {"error": "Plugin not found"}
    return {"plugin": plugin}


@router.post("/{name}/enable")
async def enable_plugin(request: Request, name: str) -> dict:
    pm = request.app.state.plugin_manager
    ctx = getattr(request.app.state, "plugin_ctx", None)
    ok = await pm.enable(name, ctx=ctx, app=request.app)
    return {"enabled": ok, "name": name}


@router.post("/{name}/disable")
async def disable_plugin(request: Request, name: str) -> dict:
    pm = request.app.state.plugin_manager
    ok = pm.disable(name)
    return {"disabled": ok, "name": name}


@router.post("/reload")
async def reload_plugins(request: Request) -> dict:
    pm = request.app.state.plugin_manager
    ctx = getattr(request.app.state, "plugin_ctx", None)
    pm.shutdown_all()
    await pm.load_all(ctx, app=request.app)
    return {"reloaded": True, "count": len([p for p in pm.list_plugins() if p["enabled"]])}
