"""FastMCP server for WHOOP health data integration."""

from fastmcp import FastMCP

from .client import WhoopClient

# Initialize MCP server
mcp = FastMCP("whoop")

# Lazy-load client
_client: WhoopClient | None = None


def get_client() -> WhoopClient:
    """Get or create WHOOP client."""
    global _client
    if _client is None:
        _client = WhoopClient()
    return _client


@mcp.tool
def get_today_data() -> dict:
    """
    Get today's complete WHOOP health data including recovery, sleep, and strain.

    Returns a dictionary with:
    - recovery: Recovery score (0-100%), HRV, resting heart rate, SpO2, skin temp, zone (green/yellow/red)
    - sleep: Total hours, efficiency %, performance %, stage breakdown, disturbances
    - strain: Day strain (0-21), calories, average and max heart rate

    Use this for daily check-ins to compare subjective feel vs objective metrics.
    """
    client = get_client()
    data = client.get_today_data()
    return data.model_dump()


@mcp.tool
def get_recovery(days: int = 7) -> list[dict]:
    """
    Get recovery scores for the specified number of days.

    Args:
        days: Number of days to retrieve (default 7, max 30)

    Returns a list of daily recovery data with:
    - date: ISO date string
    - score: Recovery score 0-100%
    - hrv: Heart rate variability in milliseconds
    - rhr: Resting heart rate in BPM
    - spo2: Blood oxygen percentage (WHOOP 4.0+)
    - skin_temp: Skin temperature in Celsius (WHOOP 4.0+)
    - zone: green (67-100), yellow (34-66), or red (0-33)

    Use for trend analysis and pattern detection over time.
    """
    days = min(max(days, 1), 30)  # Clamp to 1-30
    client = get_client()
    data = client.get_recovery_history(days)
    return [d.model_dump() for d in data]


@mcp.tool
def get_sleep(days: int = 7) -> list[dict]:
    """
    Get sleep data for the specified number of days.

    Args:
        days: Number of days to retrieve (default 7, max 30)

    Returns a list of nightly sleep data with:
    - date: ISO date string
    - total_hours: Total sleep duration
    - efficiency: Sleep efficiency percentage
    - performance: Sleep performance percentage
    - light_hours: Light sleep duration
    - deep_hours: Deep/slow-wave sleep duration
    - rem_hours: REM sleep duration
    - disturbances: Number of sleep disturbances

    Use for sleep pattern analysis and quality tracking.
    """
    days = min(max(days, 1), 30)
    client = get_client()
    data = client.get_sleep_history(days)
    return [d.model_dump() for d in data]


@mcp.tool
def get_strain(days: int = 7) -> list[dict]:
    """
    Get strain scores for the specified number of days.

    Args:
        days: Number of days to retrieve (default 7, max 30)

    Returns a list of daily strain data with:
    - date: ISO date string
    - day_strain: Daily strain score (0-21 scale, based on Borg scale)
    - calories: Energy expenditure in kilojoules
    - avg_hr: Average heart rate
    - max_hr: Maximum heart rate

    Use for training load analysis and recovery planning.

    Strain scale reference:
    - 0-9: Light activity
    - 10-13: Moderate activity
    - 14-17: High strain (e.g., surfing, MTB)
    - 18-21: All-out effort
    """
    days = min(max(days, 1), 30)
    client = get_client()
    data = client.get_strain_history(days)
    return [d.model_dump() for d in data]


@mcp.tool
def get_workouts(days: int = 7) -> list[dict]:
    """
    Get workouts/activities for the specified number of days.

    Args:
        days: Number of days to retrieve (default 7, max 30)

    Returns a list of workout data with:
    - id: Unique workout ID
    - date: Date of workout (YYYY-MM-DD)
    - time: Start time (HH:MM)
    - sport_name: Activity name (e.g., "Surfing", "Mountain Biking", "Running")
    - sport_id: WHOOP numeric sport ID
    - duration_minutes: Workout duration in minutes
    - strain: Workout strain score (0-21)
    - avg_hr: Average heart rate during workout
    - max_hr: Maximum heart rate during workout
    - calories: Energy expenditure in kilojoules

    Use this to track activities like surfing, mountain biking, training, etc.
    Workouts are automatically logged when you use the WHOOP app or strap.
    """
    days = min(max(days, 1), 30)
    client = get_client()
    data = client.get_workout_history(days)
    return [d.model_dump() for d in data]


def main():
    """Run the MCP server."""
    mcp.run()


if __name__ == "__main__":
    main()
