import django, os
from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel, Field


os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_service.settings')
django.setup()

from django_email_learning.models import Certificate

mcp = FastMCP("MCP Server")


class CertInfo(BaseModel):
    """Model representing the information of a certificate."""
    certificate_number: str = Field(..., description="The unique identifier for the certificate")
    name: str = Field(..., description="The name of the certificate holder")
    issued_date: str = Field(..., description="The date the certificate was issued")
    course: str = Field(..., description="The course associated with the certificate")
    provider: str = Field(..., description="The organization that issued the certificate")
    

@mcp.tool()
def verify_certificate(certificate_id: str) -> CertInfo | None:
    """
    Verify if a certificate with the given ID exists in the database.

    Args:
        certificate_id (str): The ID of the certificate to verify.

    Returns:
        CertInfo | None: The certificate information if it exists, None otherwise.
    """
    parts = certificate_id.split("-")
    if len(parts) != 4:
        return None
    try:
        certificate = Certificate.objects.get(id=parts[2])
    except Certificate.DoesNotExist:
        return None

    return CertInfo(
        certificate_number=certificate.certificate_number,
        name=certificate.name_on_certificate,
        issued_date=certificate.issued_at.strftime("%Y-%m-%d"),
        course=certificate.enrollment.course.title,
        provider=certificate.enrollment.course.organization.name
    )

if __name__ == "__main__":
    mcp.run()
