"""Profile management and authentication tools.

These tools handle the complete setup and auth lifecycle:
  1. check_setup_status → see what's configured
  2. setup_google_workspace → save OAuth credentials + profiles
  3. authenticate_account → open browser OAuth flow for a profile
  4. add_google_profile → add another account later
  5. list_google_profiles → show all profiles and auth status
"""

from __future__ import annotations

from typing import Optional

from fastmcp import FastMCP

from ..auth.oauth import (
    list_profiles,
    create_config,
    add_profile,
    get_setup_status,
    authenticate_profile_async,
)

mcp = FastMCP("Profiles")


@mcp.tool(tags={"setup", "profiles"})
def check_setup_status() -> dict:
    """Check if the MCP server is configured and which profiles need authentication.
    Call this first to understand what setup steps are needed."""
    return get_setup_status()


@mcp.tool(tags={"setup", "profiles"})
def setup_google_workspace(
    client_id: str,
    client_secret: str,
    profiles: list[dict],
) -> dict:
    """Configure the MCP server with Google OAuth credentials and account profiles.

    This is the first step — provide your Google Cloud OAuth Client ID/Secret
    and define your account profiles.

    Args:
        client_id: Google Cloud OAuth 2.0 Client ID
        client_secret: Google Cloud OAuth 2.0 Client Secret
        profiles: List of account profiles, each with 'name', 'email', and optional 'description'.
                  Example: [{"name": "business", "email": "me@company.com", "description": "Work account"},
                           {"name": "personal", "email": "me@gmail.com"}]
    """
    return create_config(client_id, client_secret, profiles)


@mcp.tool(tags={"setup", "profiles"})
async def authenticate_account(profile: str) -> dict:
    """Authenticate a Google account profile by opening the browser for OAuth consent.

    This opens your default browser to Google's sign-in page. Sign in with the
    email associated with this profile, grant permissions, and the token is
    saved automatically. You'll see a success message in the browser when done.

    Args:
        profile: The profile name to authenticate (e.g. 'business', 'personal')
    """
    return await authenticate_profile_async(profile)


@mcp.tool(tags={"setup", "profiles"})
def add_google_profile(
    name: str,
    email: str,
    description: str = "",
) -> dict:
    """Add a new Google account profile to an existing configuration.

    Args:
        name: Profile name (e.g. 'work2', 'shared')
        email: Gmail address for this profile
        description: Optional description
    """
    return add_profile(name, email, description)


@mcp.tool(tags={"profiles"})
def list_google_profiles() -> list[dict]:
    """List all configured Google account profiles and their authentication status."""
    return list_profiles()
