"""
Apple MCP Server - Custom MCP server for Apple native apps.
Provides integration with Messages, Notes, Reminders, Calendar, Contacts, and Photos.

All operations use local AppleScript - no network calls, no third-party dependencies.
"""

from typing import List, Dict, Any, Optional
from mcp.server.fastmcp import FastMCP

from apple_scripts import (
    # Messages
    list_message_chats,
    get_chat_messages,
    get_recent_messages,
    search_messages,
    send_imessage,
    # Notes
    list_note_folders,
    list_notes,
    get_note,
    create_note,
    search_notes,
    # Reminders
    list_reminder_lists,
    list_reminders,
    create_reminder,
    complete_reminder,
    search_reminders,
    # Calendar
    list_calendars,
    get_todays_events,
    get_events,
    create_event,
    # Contacts
    list_contacts,
    search_contacts,
    get_contact,
    get_contact_groups,
    # Photos
    list_albums,
    get_recent_photos,
    get_album_photos,
    search_photos,
)

# Initialize FastMCP server
mcp = FastMCP("apple")


# =============================================================================
# MESSAGES / iMESSAGE TOOLS
# =============================================================================

@mcp.tool()
def messages_list_chats() -> List[Dict[str, Any]]:
    """List all iMessage/SMS conversations with participant info."""
    return list_message_chats()


@mcp.tool()
def messages_get_chat(chat_id: str, limit: int = 20) -> List[Dict[str, Any]]:
    """Get messages from a specific chat.

    Args:
        chat_id: The ID of the chat to retrieve messages from
        limit: Maximum number of messages to return (default 20)
    """
    return get_chat_messages(chat_id, limit)


@mcp.tool()
def messages_get_recent(limit: int = 20) -> List[Dict[str, Any]]:
    """Get recent messages across all chats.

    Args:
        limit: Maximum number of messages to return (default 20)
    """
    return get_recent_messages(limit)


@mcp.tool()
def messages_search(query: str) -> List[Dict[str, Any]]:
    """Search messages by content.

    Args:
        query: Text to search for in message content
    """
    return search_messages(query)


@mcp.tool()
def messages_send(recipient: str, message: str) -> Dict[str, Any]:
    """Send an iMessage or SMS to a recipient.

    Args:
        recipient: Phone number or email address of the recipient
        message: The message text to send
    """
    return send_imessage(recipient, message)


# =============================================================================
# NOTES TOOLS
# =============================================================================

@mcp.tool()
def notes_list_folders() -> List[Dict[str, Any]]:
    """List all note folders with note counts."""
    return list_note_folders()


@mcp.tool()
def notes_list(folder: Optional[str] = None) -> List[Dict[str, Any]]:
    """List all notes, optionally filtered by folder.

    Args:
        folder: Optional folder name to filter notes
    """
    return list_notes(folder)


@mcp.tool()
def notes_get(note_name: str) -> Dict[str, Any]:
    """Get the content of a specific note by name.

    Args:
        note_name: The exact name of the note to retrieve
    """
    return get_note(note_name)


@mcp.tool()
def notes_create(title: str, body: str, folder: Optional[str] = None) -> Dict[str, Any]:
    """Create a new note.

    Args:
        title: Title of the note
        body: Content of the note
        folder: Optional folder to create the note in
    """
    return create_note(title, body, folder)


@mcp.tool()
def notes_search(query: str) -> List[Dict[str, Any]]:
    """Search notes by title or content.

    Args:
        query: Text to search for in note title or content
    """
    return search_notes(query)


# =============================================================================
# REMINDERS TOOLS
# =============================================================================

@mcp.tool()
def reminders_list_lists() -> List[Dict[str, Any]]:
    """List all reminder lists with counts."""
    return list_reminder_lists()


@mcp.tool()
def reminders_list(list_name: Optional[str] = None, show_completed: bool = False) -> List[Dict[str, Any]]:
    """List reminders, optionally filtered by list and completion status.

    Args:
        list_name: Optional reminder list name to filter by
        show_completed: Whether to include completed reminders (default False)
    """
    return list_reminders(list_name, show_completed)


@mcp.tool()
def reminders_create(title: str, list_name: Optional[str] = None, due_date: Optional[str] = None, notes: Optional[str] = None) -> Dict[str, Any]:
    """Create a new reminder.

    Args:
        title: Title of the reminder
        list_name: Optional list to add the reminder to
        due_date: Optional due date. Accepts various formats: 'January 30, 2026 5:00 PM',
                  '30 January 2026', '2026-01-30', '30/1/2026', etc.
        notes: Optional notes/description for the reminder
    """
    return create_reminder(title, list_name, due_date, notes)


@mcp.tool()
def reminders_complete(reminder_name: str) -> Dict[str, Any]:
    """Mark a reminder as complete.

    Args:
        reminder_name: The exact name of the reminder to complete
    """
    return complete_reminder(reminder_name)


@mcp.tool()
def reminders_search(query: str) -> List[Dict[str, Any]]:
    """Search reminders by name.

    Args:
        query: Text to search for in reminder names
    """
    return search_reminders(query)


# =============================================================================
# CALENDAR TOOLS
# =============================================================================

@mcp.tool()
def calendar_list() -> List[Dict[str, Any]]:
    """List all calendars."""
    return list_calendars()


@mcp.tool()
def calendar_today() -> List[Dict[str, Any]]:
    """Get today's calendar events across all calendars."""
    return get_todays_events()


@mcp.tool()
def calendar_events(calendar_name: Optional[str] = None, days_ahead: int = 7) -> List[Dict[str, Any]]:
    """Get upcoming events from a specific calendar or all calendars.

    Args:
        calendar_name: Optional calendar name to filter by
        days_ahead: Number of days to look ahead (default 7)
    """
    return get_events(calendar_name, days_ahead)


@mcp.tool()
def calendar_create_event(
    title: str,
    calendar_name: str,
    start_date: str,
    end_date: str,
    location: Optional[str] = None,
    notes: Optional[str] = None
) -> Dict[str, Any]:
    """Create a new calendar event.

    Args:
        title: Title of the event
        calendar_name: Name of the calendar to add the event to
        start_date: Start date/time (format: 'January 7, 2026 10:00 AM')
        end_date: End date/time (format: 'January 7, 2026 11:00 AM')
        location: Optional location for the event
        notes: Optional notes/description for the event
    """
    return create_event(title, calendar_name, start_date, end_date, location, notes)


# =============================================================================
# CONTACTS TOOLS
# =============================================================================

@mcp.tool()
def contacts_list(limit: int = 50) -> List[Dict[str, Any]]:
    """List contacts from the address book.

    Args:
        limit: Maximum number of contacts to return (default 50)
    """
    return list_contacts(limit)


@mcp.tool()
def contacts_search(query: str) -> List[Dict[str, Any]]:
    """Search contacts by name, email, or phone number.

    Args:
        query: Text to search for in contact name, email, or phone
    """
    return search_contacts(query)


@mcp.tool()
def contacts_get(name: str) -> Dict[str, Any]:
    """Get detailed information about a specific contact.

    Args:
        name: The exact name of the contact to retrieve
    """
    return get_contact(name)


@mcp.tool()
def contacts_groups() -> List[Dict[str, Any]]:
    """List all contact groups with member counts."""
    return get_contact_groups()


# =============================================================================
# PHOTOS TOOLS
# =============================================================================

@mcp.tool()
def photos_list_albums() -> List[Dict[str, Any]]:
    """List all photo albums with photo counts."""
    return list_albums()


@mcp.tool()
def photos_recent(limit: int = 20) -> List[Dict[str, Any]]:
    """Get recent photos from the library.

    Args:
        limit: Maximum number of photos to return (default 20)
    """
    return get_recent_photos(limit)


@mcp.tool()
def photos_album(album_name: str, limit: int = 20) -> List[Dict[str, Any]]:
    """Get photos from a specific album.

    Args:
        album_name: Name of the album to retrieve photos from
        limit: Maximum number of photos to return (default 20)
    """
    return get_album_photos(album_name, limit)


@mcp.tool()
def photos_search(query: str, limit: int = 20) -> List[Dict[str, Any]]:
    """Search photos by description or filename.

    Args:
        query: Text to search for in photo descriptions or filenames
        limit: Maximum number of photos to return (default 20)
    """
    return search_photos(query, limit)


# =============================================================================
# ENTRY POINT
# =============================================================================

def main():
    mcp.run(transport='stdio')


if __name__ == "__main__":
    main()
