"""PDF MCP Server using FastMCP."""

from __future__ import annotations

import logging
from typing import Optional

from fastmcp import FastMCP

from .pdf_tools import encrypt_pdf

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

mcp = FastMCP("PDF 加密")


@mcp.tool()
def encrypt_pdf_file(
    input_path: str,
    output_path: str,
    user_password: str,
    owner_password: Optional[str] = None,
    allow_printing: bool = False,
    allow_modifying: bool = False,
    allow_copying: bool = False,
    allow_annotating: bool = False,
    allow_filling_forms: bool = False,
    mode: str = "basic",
    dpi: int = 144,
    image_format: str = "png",
    quality: int = 85,
) -> str:
    """加密PDF文件并设置权限。
    
    Args:
        input_path: 输入PDF文件路径
        output_path: 输出PDF文件路径
        user_password: 用户密码（打开密码）
        owner_password: 所有者密码（权限密码）
        allow_printing: 允许打印
        allow_modifying: 允许修改
        allow_copying: 允许复制
        allow_annotating: 允许注释
        allow_filling_forms: 允许填写表单
        mode: 加密模式，"basic"(标准加密) 或 "rasterize"(光栅化加密)
        dpi: 光栅化DPI（仅在rasterize模式下使用）
        image_format: 光栅化图片格式（仅在rasterize模式下使用）
        quality: 光栅化质量（仅在rasterize模式下使用）
    
    Returns:
        加密结果的详细信息
    """
    
    try:
        permissions = {
            "printing": allow_printing,
            "modifying": allow_modifying,
            "copying": allow_copying,
            "annotating": allow_annotating,
            "fillingForms": allow_filling_forms,
        }
        result = encrypt_pdf(
            input_path,
            output_path,
            user_password,
            owner_password,
            permissions,
            mode,
            dpi,
            image_format,
            quality,
        )
        perms_info = "\n".join([
            f"  - {k}: {'✓' if v else '✗'}"
            for k, v in result.permissions.items()
        ])
        return (
            f"✅ PDF encryption succeeded\n"
            f"Output file: {result.output_path}\n"
            f"Pages: {result.page_count}\n"
            f"Mode: {result.mode}\n"
            f"Permissions:\n{perms_info}"
        )
    
    except Exception as e:
        logger.error(f"Encryption failed: {e}")
        raise e


def main():
    """启动MCP服务器。"""
    mcp.run()


if __name__ == "__main__":
    main()
