"""
PowerBI MCP Server

Main server initialization and configuration.
"""

import logging
from contextlib import asynccontextmanager
from typing import AsyncIterator

from mcp.server import FastMCP

from .auth import PowerBIAuth
from .client import PowerBIClient
from .tools import (
    register_workspace_tools,
    register_dataset_tools,
    register_query_tools
)

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def powerbi_lifespan(server: FastMCP) -> AsyncIterator[dict]:
    """
    Manage PowerBI server lifecycle

    Initializes authentication and API client on startup,
    ensures cleanup on shutdown.

    Yields:
        dict: Lifespan context with 'auth' and 'client' keys
    """
    logger.info("PowerBI MCP Server initializing...")

    # Initialize authentication (credentials validated on first use)
    auth = PowerBIAuth()
    logger.info("Authentication handler created")

    # Initialize API client
    client = PowerBIClient(auth)
    logger.info("PowerBI API client created")

    # Yield context to server
    try:
        logger.info("PowerBI MCP Server ready")
        yield {"auth": auth, "client": client}
    finally:
        # Cleanup on shutdown
        logger.info("PowerBI MCP Server shutting down...")
        await client.close()
        await auth.close()
        logger.info("PowerBI MCP Server stopped")


# Initialize MCP server with FastMCP
mcp = FastMCP(
    name="powerbi-mcp",
    instructions=(
        "A Model Context Protocol server for PowerBI REST API. "
        "Provides tools to list workspaces, browse datasets, and execute DAX queries. "
        "Requires Azure AD service principal authentication."
    ),
    lifespan=powerbi_lifespan
)

# Register all tools
logger.info("Registering tools...")
register_workspace_tools(mcp)
register_dataset_tools(mcp)
register_query_tools(mcp)
logger.info("All tools registered")
