#!/usr/bin/env python3
"""
Granola MCP Server

Access meeting notes and transcripts from the Granola desktop app.
Requires Granola to be installed on macOS.

Run with:
  uvx granola-mcp
  # or
  python -m granola_mcp
"""

from mcp.server.fastmcp import FastMCP
from typing import Literal

from granola_mcp.client import (
    GranolaAPIClient,
    api_search_meetings as _api_search_meetings,
    api_get_transcript as _api_get_transcript,
)

# Create MCP server
mcp = FastMCP(
    "granola",
    instructions="Granola - Access meeting notes and transcripts"
)


@mcp.tool()
def find_recent_meetings(limit: int = 5) -> dict:
    """
    Get a list of recent Granola meetings with their titles, dates, attendees,
    and whether they have transcripts.

    Use this to browse recent meetings before getting a specific transcript.

    Args:
        limit: Number of recent meetings to return (default: 5, max: 50)
    """
    client = GranolaAPIClient()
    try:
        results = client.get_recent_meetings(limit=limit)
        return {
            "success": True,
            "count": len(results),
            "meetings": [
                {
                    "id": m.id,
                    "title": m.title,
                    "date": m.date,
                    "date_formatted": m.date_formatted,
                    "attendees": m.attendees,
                    "has_transcript": m.has_transcript,
                    "has_notes": m.has_notes,
                    "notes_summary": m.notes_summary,
                }
                for m in results
            ],
        }
    except Exception as e:
        return {"success": False, "error": str(e), "meetings": []}


@mcp.tool()
def search_meetings(
    query: str,
    search_in: Literal["title", "attendees", "notes", "all"] = "all"
) -> dict:
    """
    Search for Granola meetings by title, attendee name, or content in notes.

    Returns matching meetings with relevance scores.

    Args:
        query: Search query - can be a person's name, meeting title, or keyword from notes
        search_in: Where to search - "title", "attendees", "notes", or "all" (default: "all")
    """
    return _api_search_meetings(query=query, search_in=search_in)


@mcp.tool()
def get_transcript(meeting_id: str) -> dict:
    """
    Get the full transcript of a specific Granola meeting.

    Requires the meeting ID which can be obtained from find_recent_meetings
    or search_meetings.

    Args:
        meeting_id: The unique ID of the meeting (UUID format)
    """
    return _api_get_transcript(meeting_id=meeting_id)


def main():
    """Entry point for the MCP server."""
    mcp.run()


if __name__ == "__main__":
    main()
