"""
Workspace management tools

Tools for listing and managing PowerBI workspaces.
"""

import json
import logging
from typing import Optional

from mcp.server import FastMCP
from mcp.server.fastmcp import Context

from ..models import ResponseFormat, DetailLevel
from ..formatters import (
    format_workspaces_markdown,
    format_reports_markdown,
    truncate_response
)
from ..constants import MAX_WORKSPACES_TOP, MIN_WORKSPACES_TOP

logger = logging.getLogger(__name__)


def register_workspace_tools(mcp: FastMCP) -> None:
    """Register workspace-related tools with the MCP server"""

    @mcp.tool()
    async def get_workspaces(
        top: Optional[int] = None,
        skip: Optional[int] = None,
        format: str = "markdown",
        detail: str = "concise",
        ctx: Context = None
    ) -> str:
        """
        Get list of PowerBI workspaces (also called groups) accessible to the service principal.

        This tool retrieves all workspaces that the configured service principal has access to.
        Workspaces are containers for dashboards, reports, datasets, and dataflows in PowerBI.

        Use this when you need to:
        - Discover available workspaces
        - Find a workspace ID for further operations
        - List all accessible PowerBI workspaces

        Parameters:
        - top (optional): Maximum number of workspaces to return (1-5000, for pagination)
        - skip (optional): Number of workspaces to skip (for pagination)
        - format: Response format - "json" or "markdown" (default: "markdown")
        - detail: Detail level - "concise" or "detailed" (default: "concise")

        Returns:
        List of workspaces with their IDs, names, and optionally detailed metadata.

        Example usage:
        - Get first 10 workspaces: top=10
        - Get concise markdown list: format="markdown", detail="concise"
        - Get detailed JSON: format="json", detail="detailed"

        Error handling:
        - If authentication fails, check your service principal credentials
        - If no workspaces returned, ensure service principal has workspace access
        - For permission errors, verify service principal is enabled in PowerBI admin portal
        """
        try:
            # Validate parameters
            if top is not None and (top < MIN_WORKSPACES_TOP or top > MAX_WORKSPACES_TOP):
                return f"Error: 'top' parameter must be between {MIN_WORKSPACES_TOP} and {MAX_WORKSPACES_TOP}"

            if skip is not None and skip < 0:
                return "Error: 'skip' parameter must be non-negative"

            format_type = ResponseFormat(format.lower())
            detail_level = DetailLevel(detail.lower())

            # Get client from context
            client = ctx.request_context.lifespan_context["client"]

            await ctx.info(f"Fetching workspaces (top={top}, skip={skip})")

            # Fetch workspaces from API
            result = await client.get_workspaces(top=top, skip=skip)
            workspaces = result.get("value", [])

            await ctx.info(f"Found {len(workspaces)} workspaces")

            # Format response
            if format_type == ResponseFormat.MARKDOWN:
                response = format_workspaces_markdown(workspaces, detail_level)
            else:
                response = json.dumps(workspaces, indent=2)

            return truncate_response(response)

        except ValueError as e:
            error_msg = f"Invalid parameter value: {str(e)}"
            await ctx.error(error_msg)
            return f"Error: {error_msg}"
        except Exception as e:
            error_msg = str(e)
            await ctx.error(f"Failed to get workspaces: {error_msg}")
            return f"Error executing get_workspaces: {error_msg}"

    @mcp.tool()
    async def get_reports(
        workspace_id: Optional[str] = None,
        format: str = "markdown",
        detail: str = "concise",
        ctx: Context = None
    ) -> str:
        """
        Get PowerBI reports from a workspace.

        Returns report information including:
        - Report name and ID
        - Web URL for viewing
        - Embed URL for embedding
        - Associated dataset ID

        Useful for discovering available reports and getting report URLs.

        Parameters:
        - workspace_id (optional): Workspace ID. Omit to get reports from "My workspace"
        - format: Response format - "json" or "markdown" (default: "markdown")
        - detail: Detail level - "concise" or "detailed" (default: "concise")

        Returns:
        List of reports with their IDs, names, and optionally URLs and dataset IDs.

        Example usage:
        - Get reports from My workspace: (omit workspace_id)
        - Get reports from specific workspace: workspace_id="abc123"
        - Get detailed info with URLs: detail="detailed"

        Error handling:
        - If workspace_id not found, verify the ID using get_workspaces
        - For permission errors, ensure service principal has read access
        - Empty list means no reports in the workspace or no access
        """
        try:
            format_type = ResponseFormat(format.lower())
            detail_level = DetailLevel(detail.lower())

            # Get client from context
            client = ctx.request_context.lifespan_context["client"]

            if workspace_id:
                await ctx.info(f"Fetching reports from workspace {workspace_id}")
            else:
                await ctx.info("Fetching reports from My workspace")

            # Fetch reports from API
            result = await client.get_reports(workspace_id=workspace_id)
            reports = result.get("value", [])

            await ctx.info(f"Found {len(reports)} reports")

            # Get workspace name for formatting
            workspace_name = "My workspace"
            if workspace_id:
                workspaces_result = await client.get_workspaces()
                workspaces = workspaces_result.get("value", [])
                workspace = next((w for w in workspaces if w.get("id") == workspace_id), None)
                if workspace:
                    workspace_name = workspace.get("name", workspace_id)

            # Format response
            if format_type == ResponseFormat.MARKDOWN:
                response = format_reports_markdown(reports, workspace_name, detail_level)
            else:
                response = json.dumps(reports, indent=2)

            return truncate_response(response)

        except ValueError as e:
            error_msg = f"Invalid parameter value: {str(e)}"
            await ctx.error(error_msg)
            return f"Error: {error_msg}"
        except Exception as e:
            error_msg = str(e)
            await ctx.error(f"Failed to get reports: {error_msg}")
            return f"Error executing get_reports: {error_msg}"

    logger.info("Workspace tools registered")
